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 Lambda Stream及其实现类常用函数
java·后端·spring
2501_941982054 分钟前
Java 分布式环境下的 Access_Token 一致性方案:如何避免多节点冲突?
java·开发语言·分布式
历程里程碑13 分钟前
哈希3 : 最长连续序列
java·数据结构·c++·python·算法·leetcode·tornado
chilavert31816 分钟前
技术演进中的开发沉思-328 JVM:垃圾回收(上)
java·开发语言·jvm
椰羊~王小美20 分钟前
前后端 格式化货币的方法
java·前端
heartbeat..22 分钟前
数据库性能优化:优化的时机(表结构+SQL语句+系统配置与硬件)
java·数据库·mysql·性能优化
带刺的坐椅26 分钟前
开发 Java MCP 就像写 Controller 一样简单,还支持 Java 8
java·llm·solon·mcp·skills
小唐同学爱学习27 分钟前
缓存与数据库一致性问题
java·数据库·spring boot·缓存
没有bug.的程序员34 分钟前
Spring Boot 数据访问:JPA 与 MyBatis 集成对比与性能优化深度解密
java·spring boot·性能优化·mybatis·jpa·集成对比