我有一个具有以下结构的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);
}
}
当我启动应用程序时,Component1
和Component2
都被标识为候选组件。但是,仅实例化Component1
。
Component2
只会在我进行以下任一更改时实例化
com.package
,即与Component1
@Autowired
com.package.Configuration
字段
醇>
为什么Spring Boot会发现组件但在这种情况下不会实例化它? @ComponentScan
在发现与实例化@Component
方面有何不同?
答案 0 :(得分:0)
在我的情况下,它不是Spring Boot本身的问题。
@PostConstruct
的{{1}}方法阻止了主线程,因此Component1
未初始化。
使用Component2
或移动到同一个包显然会在@Autowired
之前触发@PostConstruct
Component2
方法。