为什么 Spring Boot 发现但不实例化 @Component? [英] Why does Spring Boot discover but not instantiate a @Component?

查看:79
本文介绍了为什么 Spring Boot 发现但不实例化 @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);
  }
} 

当我启动应用程序时,Component1Component2 都被标识为候选组件.但是,只有 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

  1. 我将它移动到 com.package,即与 Component1
  2. 相同
  3. 我将其声明为 com.package.Configuration
  4. 中的 @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆