Why does Spring Boot discover but not instantiate a @Component?

本秂侑毒 提交于 2021-02-18 22:55:55

问题


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

My application class is

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);
  }
} 

When I start the application both Component1 and Component2 are identified as candidate components. However, only Component1 is instantiated.

Component2 will only instantiate when I make either of the following changes

  1. I move it to com.package i.e. the same as Component1
  2. I declare it as a @Autowired field in com.package.Configuration

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?


回答1:


In my case it was not an issue with Spring Boot itself.

The @PostConstruct method for Component1 was blocking the main thread hence Component2 was not initialised.

Using @Autowired or moving to the same package obviously triggered the @PostConstruct method of Component2 before Component1.



来源:https://stackoverflow.com/questions/45733297/why-does-spring-boot-discover-but-not-instantiate-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!