gpt4 book ai didi

java - 如何以编程方式将 @Bean 定义添加到 Spring 上下文?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:56 24 4
gpt4 key购买 nike

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

@Autowired
private SpringBus bus;

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

但现在我需要对流程进行更深入的控制,尤其是我想动态创建注册 bean 的 bean 名称。

我试过:

@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,因为这里还没有初始化 Autowiring 的依赖项!

那么,我如何以编程方式添加这些 bean?

最佳答案

你应该把这个放在:

beanFactory.autowireBean(port);

但是,如果您想初始化一个 bean,我认为您想要创建一个实例(我这样说是因为在示例中,您使用了 @Bean 注释):

beanFactory.initializeBean(port, "myDynamicPortName");  

而不是单例:

beanFactory.registerSingleton("myDynamicPortName", port);

关于java - 如何以编程方式将 @Bean 定义添加到 Spring 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27266608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com