有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

有没有其他方法可以做到这一点


共 (2) 个答案

  1. # 1 楼答案

    怎么样

    @Bean
    public ContextDataConfiguration contextDataConfiguration(){
        return new ContextDataConfiguration();
    }
    

    这将ContextDataConfiguration的实例注册为bean

  2. # 2 楼答案

    您可以在工厂方法中使用@Bean注释来初始化Bean。所以,假设您有一个MyBean组件,并希望对其进行初始化。。。您可以在@Configuration类中执行此操作:

    @Bean
    public MyBean myBean() {
       MyBean myBean = ... // initialize your bean here
    
       return myBean;
    }