当前位置: 首页 > news >正文

SpringBoot运行时注入一个Bean

描述

使用GenericApplicationContext类的registerBean方法可以在项目运行时注入一个bean,获取GenericApplicationContext可以继承ApplicationContextAware,重写setApplicationContext,里面的参数就是ApplicationContext。

继承ApplicationContextAware

@RestController
@RequestMapping("/register/bean")
public class RegisterBeanController implements ApplicationContextAware {private ApplicationContext applicationContext;// AnnotationConfigServletWebServerApplicationContext@GetMapping("/example")public String registerBean() {GenericApplicationContext genericApplicationContext = (GenericApplicationContext) this.applicationContext;// ExampleBean没有使用任何的Component注解。genericApplicationContext.registerBean("ExampleBean", ExampleBean.class);ExampleBean exampleBean = (ExampleBean) applicationContext.getBean("ExampleBean");return exampleBean.getBeanData().getName();}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}
}

BeanData

@Component
public class BeanData {public String getName() {return "BeanData";}
}

ExampleBean

测试@Autowrite是否生效。

public class ExampleBean {private String name;@Autowiredprivate BeanData beanData;public String getName() {return name;}public void setName(String name) {this.name = name;}public BeanData getBeanData() {return beanData;}
}
http://www.lryc.cn/news/111651.html

相关文章:

  • Pyspark
  • Spring Boot 项目五维度九层次分层架构实现实践研究——持续更新中
  • stm32常见数据类型
  • mac m1使用docker安装kafka
  • SpringBoot核心配置和注解
  • 第三章 图论 No.3 flody之多源汇最短路,传递闭包,最小环与倍增
  • Leetcode-每日一题【剑指 Offer 17. 打印从1到最大的n位数】
  • 远程调试MySQL内核
  • 前端学习---vue2--选项/数据--data-computed-watch-methods-props
  • UML-构件图
  • uniapp使用视频地址获取视频封面
  • java操作PDF:转换、合成、切分
  • 递增子序列——力扣491
  • 解密!品牌独立站为何能成为外国消费者的心头爱?
  • 【HDFS】每天一个RPC系列----complete(二):客户端侧
  • 五、PC远程控制ESP32 LED灯
  • 详解PHP反射API
  • 打开虚拟机进行ip addr无网络连接
  • Spring Boot如何整合mybatisplus
  • webpack基础知识一:说说你对webpack的理解?解决了什么问题?
  • 小研究 - 基于 MySQL 数据库的数据安全应用设计(二)
  • 大数据-数据内容分类
  • Babel编译与Webpack
  • 0805hw
  • ROS实现机器人移动
  • Dockerfile构建LNMP镜像
  • 总结七大排序!
  • 没有fastjson,rust怎么方便的解析提取复杂json呢?
  • Docker制作SpringBoot镜像
  • 力扣:53. 最大子数组和(Python3)