为什么Spring Boot会发现但不实例化@Component?

时间:2017-08-17 10:58:59

标签: java spring spring-boot

我有一个具有以下结构的Spring Boot应用程序

com.package
   Application - annotated with @SpringBootApplication
   Configuration - annotated with @Configuration
   Component1 - annotated with @Component, constructor annotated with @Autowired
com.package.subpackage
   Component2 - annotated with @Component, constructor annotated with @Autowired

我的申请类是

package com.package;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application
{
  public static void main(String[] args)
  {
    SpringApplication.run(Application.class, args);
  }
} 

当我启动应用程序时,Component1Component2都被标识为候选组件。但是,仅实例化Component1

Component2只会在我进行以下任一更改时实例化

  1. 我将其移至com.package,即与Component1
  2. 相同
  3. 我在@Autowired
  4. 中将其声明为com.package.Configuration字段

    为什么Spring Boot会发现组件但在这种情况下不会实例化它? @ComponentScan在发现与实例化@Component方面有何不同?

1 个答案:

答案 0 :(得分:0)

在我的情况下,它不是Spring Boot本身的问题。

@PostConstruct的{​​{1}}方法阻止了主线程,因此Component1未初始化。

使用Component2或移动到同一个包显然会在@Autowired之前触发@PostConstruct Component2方法。