0

I'm trying to understand the transition from using xml annotation to java based annotation in Spring. I have these definitions

<context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml.

<context:component-scan>: Bean registration + <context:annotation-config>

is @Configuration and is @ComponentScan.

If lets say I declare all my beans with @Component (disregard first the more specific ones like @Repository, @Service etc) annotation and make sure that the packages are getting scanned by the @ComponentScan annotation, what is a particular use case where I will still annotate my class with both @Configuration together with @ComponentScan?

I ask this question because sometimes I see classes annotated with both @Configuration and @ComponentScan at the same time.

bencampbell_14
  • 587
  • 2
  • 10
  • 32

2 Answers2

1

First read the following carefully:

Difference between <context:annotation-config> vs <context:component-scan>

Thus <context:component-scan> does the scan job and the same job than <context:annotation-config> does, it means work around with the DI annotations

Then now consider:

  • <context:component-scan> equivalent to @ComponentScan
  • <context:annotation-config> no equivalent for annotation.

what is a particular use case where I will still annotate my class with both @Configuration together with @ComponentScan?

@Configuration is used to define beans about Infastructure such as Database, JMS etc...

Yes, a class can use both, It could be used for example for MVC Infrastructure @Configuration such as:

@EnableWebMvc
@Configuration
@ComponentScan("com.manuel.jordan.controller", "com.manuel.jordan.rest")
public class WebMvcConfig extends WebMvcConfigurerAdapter {

Thus from that class your are configuring MVC and indicating only to scan the MVC classes created by you for the "web side", such as: @Controller, @RestController.

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
0

This really depends on your likings and coding style. Documentation states:

Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

So every time you see just @ComponentScan annotation this means that all sub-packages should be scanned. This is a reasonable approach to take with package per feature layout: when you have a @Configuration class for your feature and all @Components related to the feature in sub-packages.

Aleh Maksimovich
  • 2,622
  • 8
  • 19