为什么 Spring Boot 发现但不实例化 @Component? [英] Why does Spring Boot discover but not instantiate a @Component?
问题描述
我有一个具有以下结构的 Spring Boot 应用程序
I have a Spring Boot application with the following structure
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
被实例化.
When I start the application both Component1
and Component2
are identified as candidate components. However, only Component1
is instantiated.
Component2
只会在我进行以下任一更改时实例化
Component2
will only instantiate when I make either of the following changes
- 我将它移动到
com.package
,即与Component1
相同 - 我将其声明为
com.package.Configuration
中的
@Autowired
字段在这种情况下,为什么 Spring Boot 会发现组件但不实例化它?@ComponentScan
在发现和实例化 @Component
方面的工作方式是否存在差异?
Why does Spring Boot discover the component but not instantiate it in this case? Are there differences in how @ComponentScan
works with regards to discovering vs instantiating @Component
?
推荐答案
就我而言,这不是 Spring Boot 本身的问题.
In my case it was not an issue with Spring Boot itself.
Component1
的 @PostConstruct
方法阻塞了主线程,因此 Component2
没有初始化.
The @PostConstruct
method for Component1
was blocking the main thread hence Component2
was not initialised.
使用@Autowired
或者移动到同一个包明显触发了Component1
之前Component2
的@PostConstruct
方法.
Using @Autowired
or moving to the same package obviously triggered the @PostConstruct
method of Component2
before Component1
.
这篇关于为什么 Spring Boot 发现但不实例化 @Component?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!