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

Mar*_*ark 6 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
Run Code Online (Sandbox Code Playgroud)

我的应用程序类是

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);
  }
} 
Run Code Online (Sandbox Code Playgroud)

当我都启动应用程序Component1Component2被确定为候选组件.但是,仅Component1实例化.

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

  1. 我将它移动到com.packageieComponent1
  2. 我把它声明为一个@Autowired字段com.package.Configuration

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

Mar*_*ark 1

就我而言,这不是 Spring Boot 本身的问题。

@PostConstruct方法Component1阻塞了主线程,因此Component2未初始化。

使用@Autowired或移动到同一个包显然会触发before@PostConstruct的方法。Component2Component1