简体   繁体   中英

Spring @Import values are plain classes without @Configuration

Refer to the code, the imported "SomeController.class" do not annotated with @Configuration,@Controller or @Component, but it is indeed worked.

Is it reasonable, any potential problems here?

@Import(SomeController.class)
@Configuration
public class MyConfiguration{
}


public class SomeController{
    @Inject SomeService someService;
    ....
}

I'm the asker. Here is my conclusion with my testing:

Using @Import(Any.class) and Any.class is not under Spring component scan scope:
1. If Any.class do not annotated with any annotations, Spring will create the bean named by full class: com.xxx.Any

  1. If Any.class annotated with @Component and so on, Spring will create the bean named by full class: com.xxx.Any

  2. If Any.class annotated with @Component("anyBean") and so on, Spring will create the bean named : anyBean

BTW, If Any.class is under Spring component scan scope, we do not need @Import it, and Spring will create the bean named : any

Scanning/importing etc is only required to find beans which otherwise will not be found. If Spring sees bean is required then it will load and initialize it anyway.

For example,

@Service
public class MyService {
  @Autowire MyComponent myComponent;
}

Even if MyComponent is not marked by any annotation and not imported by any @Import then it will be instantiated by Spring just because it is required for MyService .

You can think of @Import etc as entry points for Spring, ie where to start to look for beans and then it will pull whole hierarchy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM