如何以编程方式将@Bean定义添加到Spring上下文? [英] How to programatically add an @Bean definition to Spring context?

查看:79
本文介绍了如何以编程方式将@Bean定义添加到Spring上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常情况下,我使用 @Bean 定义将我的对象添加到spring上下文中:

Normally I'm adding my objects to spring context using @Bean definition:

@Autowired
private SpringBus bus;

//register a singleton
@Bean
public WebservicePort getPort() {
    //new port()
    //initialize
    //configure
    //return port;
}

但现在我需要更深入地控制流程,特别是我想要创建Bean名称动态地注册bean。

But now I need deeper control of the process, especially I want to create the bean name dynamically under which the bean is registered.

我试过:

@Service
public class MyPortRegistrar implements BeanDefinitionRegistryPostProcessor {

        @Autowired
        private SpringBus bus;

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            System.out.println(bus); //prints null

            //create and configure port with the SpringBus
            Port port = new WebservicePort(bus); // -> throws NullPointerException
            beanFactory.autowireBean(port);
            beanFactory.initializeBean(port, "myDynamicPortName");  
        }
}

但这会引发NPE,因为自动连接的家属不是但是在这里初始化了!

But this throws an NPE as the autowired dependecies are not yet initialized here!

那么,我怎样才能以编程方式添加这些bean?

So, how can I add those beans programatically?

推荐答案

您应该自动装配bean工厂,并使用 @PostConstruct 来注册您的bean。这样,您可以保证所有依赖项都已注入(bean工厂由容器注入,无需设置)。

You should autowire the bean factory, and use a @PostConstruct to register your bean. That way, you guarantee that all dependencies has been injected (the bean factory is injected by the container, no setup is needed).

@Service
public class MyPortRegistrar {

    @Autowired
    private ConfigurableBeanFactory beanFactory;

    @Autowired
    private SpringBus bus;

    @PostConstruct
    public void createPort() {
        Port port = new WebservicePort(bus);
        beanFactory.registerSingleton("myDynamicPortName", port);
    }
}

这篇关于如何以编程方式将@Bean定义添加到Spring上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆