以编程方式注册@Component注释类

时间:2018-03-06 11:59:49

标签: java spring spring-boot spring-data-jpa spring-bean

我是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类它正在工作,但它给我一个错误,如

  

不是托管类型

有没有其他方法可以帮助我。

2 个答案:

答案 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。