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;
    }
}
相关推荐
apcipot_rain3 小时前
C++转Java日记(06)
java·开发语言
金銀銅鐵7 小时前
带您看懂字节码指令(一):一帧里有什么
java·后端·ai编程
nice_lcj5209 小时前
【从零理解 Spring AI · 14】RAG 的四个环节:加载、切分、向量化、检索
java·spring boot·embedding·向量数据库·rag·spring ai·ai应用开发
学长毕设11 小时前
基于springboot科创竞赛信息平台-附源码
java·spring boot·后端
聪明的笨猪猪11 小时前
Java 工程案例:AI 生成 @Async 异步线程池踩坑
java·经验分享·面试·ai编程
学长毕设11 小时前
基于SpringBoot公务员考试交流平台-附源码
java·spring boot·后端
SL_staff14 小时前
私有化低代码:面向强监管行业的可控数字化实践
java·低代码
三翼鸟数字化技术团队14 小时前
高性能存储引擎RocksDB:原理与Java生态实践
java
AI开源软件15 小时前
SpringBoot3+AI Agent 智能报销:怎样把对话接进现有财务审批系统
spring boot·ai agent·人工确认·ruoyi office·agentos·智能报销·财务审批
SL_staff15 小时前
JVS-APS有限产能建模的七个刚性支点:面向产线真实约束的技术实现解析
java·开源·全栈