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;
    }
}
相关推荐
此木|西贝2 小时前
【设计模式】享元模式
java·设计模式·享元模式
李少兄3 小时前
解决Spring Boot多模块自动配置失效问题
java·spring boot·后端
bxlj_jcj3 小时前
JVM性能优化之年轻代参数设置
java·性能优化
八股文领域大手子3 小时前
深入理解缓存淘汰策略:LRU 与 LFU 算法详解及 Java 实现
java·数据库·算法·缓存·mybatis·哈希算法
不当菜虚困3 小时前
JAVA设计模式——(八)单例模式
java·单例模式·设计模式
m0_740154673 小时前
Maven概述
java·maven
他҈姓҈林҈4 小时前
Spring Boot 支持政策
spring boot
吗喽对你问好4 小时前
Java位运算符大全
java·开发语言·位运算
Java致死4 小时前
工厂设计模式
java·设计模式·简单工厂模式·工厂方法模式·抽象工厂模式