SpringBoot运行时注入一个Bean

描述

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

继承ApplicationContextAware

java 复制代码
@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();
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

BeanData

java 复制代码
@Component
public class BeanData {
    public String getName() {
        return "BeanData";
    }
}

ExampleBean

测试@Autowrite是否生效。

java 复制代码
public class ExampleBean {
    private String name;
	
    @Autowired
    private BeanData beanData;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BeanData getBeanData() {
        return beanData;
    }
}
相关推荐
forestsea42 分钟前
Java虚拟机面试题:内存管理(上)
java·开发语言
吾零鬼泣44 分钟前
腾讯音乐一面
spring boot·java-rocketmq·java-zookeeper
yueyekkx1 小时前
Ubuntu24.04 LTS安装java8、mysql8.0
java·mysql·ubuntu
若水uy1 小时前
静态分配动态绑定
java
程序员buddha1 小时前
SpringBoot多环境配置文件切换
java·spring boot·后端
Java小白笔记1 小时前
IDEA中创建SpringBoot项目没有Java8
java·spring boot·intellij-idea
呦呦鹿鸣Rzh2 小时前
默认登陆界面的生成
java
长勺2 小时前
单例模式总结
java·开发语言·单例模式
zzhongcy2 小时前
【容易坑】mybatis中使用if标签比较两个字符串是否相等
java·tomcat·mybatis
twj_one2 小时前
SpringBoot+ELK 搭建日志监控平台
spring boot·后端·elk