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;
    }
}
相关推荐
ะัี潪ิื7 分钟前
springboot加载本地application.yml和加载Consul中的application.yml配置反序列化LocalDate类型差异
spring boot·consul·java-consul
李慕婉学姐1 小时前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
m0_740043731 小时前
SpringBoot05-配置文件-热加载/日志框架slf4j/接口文档工具Swagger/Knife4j
java·spring boot·后端·log4j
编织幻境的妖1 小时前
SQL查询连续登录用户方法详解
java·数据库·sql
未若君雅裁2 小时前
JVM面试篇总结
java·jvm·面试
kk哥88992 小时前
C++ 对象 核心介绍
java·jvm·c++
招风的黑耳2 小时前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
xunyan62342 小时前
面向对象(下)-接口的理解
java·开发语言
大佐不会说日语~2 小时前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
Miss_Chenzr2 小时前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端