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;
    }
}
相关推荐
萤丰信息4 分钟前
智慧园区能源革命:从“耗电黑洞”到零碳样本的蜕变
java·大数据·人工智能·科技·安全·能源·智慧园区
曹牧30 分钟前
Eclipse为方法添加注释
java·ide·eclipse
我叫张小白。1 小时前
Spring Boot拦截器详解:实现统一的JWT认证
java·spring boot·web·jwt·拦截器·interceptor
Gerardisite3 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
q***69773 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
闲人编程4 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
故渊ZY4 小时前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
匿者 衍4 小时前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel
一个尚在学习的计算机小白4 小时前
java集合
java·开发语言
IUGEI4 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#