Why does Spring Boot detect but not instantiate @Component?

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

 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 the application starts, both Component1 and Component2 identified as candidate components. However, only Component1 is created.

Component2 will only execute after I make one of the following changes

  • Move it to com.package , i.e. to Component1
  • I declare it as a @Autowired field in com.package.Configuration

Why does Spring Boot detect the component but not create it in this case? Are there any differences in how @ComponentScan works with respect to detecting and instantiating @Component ?

+5
source share
1 answer

In my case, this is not a problem with Spring loading itself.

The @PostConstruct method for Component1 blocked the main thread, so Component2 not initialized.

Using @Autowired or moving to the same package explicitly called the @PostConstruct Component2 method before Component1 .

0
source

Source: https://habr.com/ru/post/1270958/


All Articles