java以编程方式注册@Component注释类
我是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类,它可以工作,但它会给我一个错误,如
not a managed type class
有没有其他方法可以做到这一点
# 1 楼答案
怎么样
这将
ContextDataConfiguration
的实例注册为bean# 2 楼答案
您可以在工厂方法中使用@Bean注释来初始化Bean。所以,假设您有一个
MyBean
组件,并希望对其进行初始化。。。您可以在@Configuration类中执行此操作: