我是Spring框架的新手,我的问题是通过spring应用程序上下文注册spring组件我尝试了很多不同的方法,但没有运气。
@Configuration
@ComponentScan("com.example.app")
@EnableAutoConfiguration
public class ContextDataConfiguration
{
...
}
用
注册@PostConstruct
public void initilize()
{
AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
beanFactory.initializeBean( new ContextDataConfiguration(), "contextDataConfiguration" );
}
但是使用这种方法没有初始化ContextDataConfiguration类中指定的其他bean。
如果我在组件扫描中指定了ContextDataConfiguration类它正在工作,但它给我一个错误,如
不是托管类型
有没有其他方法可以帮助我。
答案 0 :(得分:1)
您可以在工厂方法中使用@Bean批注来初始化bean。所以,假设您有一个MyBean
组件并想要初始化它...您可以在@Configuration类中执行此操作:
@Bean
public MyBean myBean() {
MyBean myBean = ... // initialize your bean here
return myBean;
}
答案 1 :(得分:0)
如何约会
@Bean
public ContextDataConfiguration contextDataConfiguration(){
return new ContextDataConfiguration();
}
这会将ContextDataConfiguration
的实例注册为bean。