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 小时前
第04篇:K8s 弹性伸缩实战:HPA、VPA、KEDA——Java SaaS 应对流量洪峰的秘密武器
java·容器·kubernetes·弹性伸缩·自动扩容·ai 推理伸缩
石山代码6 小时前
ArrayList / HashMap / ConcurrentHashMap
java·开发语言
AskHarries7 小时前
系统提示词、开发者指令和用户输入的优先级
java·前端·数据库
daidaidaiyu8 小时前
ThingsBoard 规则链系统源码分析和自定义定时器
java
小毛驴8508 小时前
spring-boot-maven-plugin,maven-compiler-plugin 功能对比
java·python·maven
csdn_aspnet9 小时前
Java 霍尔分区算法(Hoare‘s Partition Algorithm)
java·开发语言·算法
霸道流氓气质9 小时前
通义灵码 IDEA 插件完全使用指南
java·ide·intellij-idea
诸葛务农9 小时前
道路行驶条件下电动汽车永磁电机的有效使用寿命及永磁体的失效和回收再利用(下)
java·开发语言·算法
Percep_gan9 小时前
Java8中的stream的测试使用
java
砍材农夫9 小时前
物联网实战:Spring Boot MQTT | MQTT 设备模拟器演示(附源码)
java·spring boot·后端·物联网·spring·netty