spring boot 动态注入bean

SpringContextUtil

public class SpringContextUtil {
    private static ApplicationContext applicationContext;
    //获取上下文
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    //设置上下文
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }
    //通过名字获取上下文中的bean
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }
    //通过类型获取上下文中的bean
    public static Object getBean(Class<?> requiredType){
        return applicationContext.getBean(requiredType);
    }
}

启动类

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext app =  SpringApplication.run(Application.class, args);
        SpringContextUtil.setApplicationContext(app);
    }
}

测试bean

@Component
public class TestService {
    public String doService(String contxt){
        System.err.printf(contxt+"hello service");
        return  "hello service";
    }
}

//无注入
public class TestController implements InitializingBean {

    @Autowired
    private TestService testService;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("我是动态注册的你,不是容器启动的时候注册的你");
    }

    public String toAction(String content){
        return "-->" +  testService.doService(content);
    }
}

测试

@RestController
public class CallCSBController {

    @GetMapping("/bean")
    public String registerBean() {
        //将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringContextUtil.getApplicationContext();

        // 获取bean工厂并转换为DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();

        // 通过BeanDefinitionBuilder创建bean定义
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(TestController.class);

        // 设置属性userService,此属性引用已经定义的bean:userService,这里userService已经被spring容器管理了.
//        beanDefinitionBuilder.addPropertyReference("testService", "testService");

        // 注册bean
        defaultListableBeanFactory.registerBeanDefinition("testController", beanDefinitionBuilder.getRawBeanDefinition());


        TestController userController = (TestController) SpringContextUtil.getBean("testController");

        return userController.toAction("动态注册生成调用");

        //删除bean.
        //defaultListableBeanFactory.removeBeanDefinition("testService");
    }
}
    原文作者:木木_bfe8
    原文地址: https://www.jianshu.com/p/41c716e7c31b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞