通常,我会使用@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,因为Autowired依赖项在此处尚未初始化!那么,我该如何以编程方式添加这些bean呢?