Use specializations of `@Component` for specific use cases

The Spring Framework provides several specializations of the generic @Component stereotype annotation which better express the programmer’s intent.

Quoting from the Spring documentation on stereotype annotations:

[…] @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with @Component, but, by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. […] Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice.

Consequently, a Spring component named

  • ...Service, ...ServiceImpl or similar should probably be annotated with @Service instead of @Component.
  • ...Repository or ...Repo or similar should probably be annotated with @Repository instead of @Component.
  • ...Controller, ...ControllerImpl or similar should probably be annotated with @Controller (or @RestController) instead of @Component.

Noncompliant code examples

@Component // Noncompliant; class name suggests it's a @Service
public class CustomerServiceImpl { 
  // ...
}
@Component // Noncompliant; class name suggests it's a @Repository
public class ProductRepository { 
    // ...
}
@Component // Noncompliant; class name suggests it's a @Controller or @RestController
public class FooBarRestController { 
    // ...
}

Compliant code examples

@Service // Compliant
public class CustomerServiceImpl { 
  // ...
}
@Repository // Compliant
public class ProductRepository { 
    // ...
}
@RestController // Compliant
public class FooBarRestController { 
    // ...
}
@Component // Compliant
public class SomeOtherComponent {
   // ...
}

Type

Code Smell

Severity

Minor

Tags

  • spring
  • design
  • bad-practice

hello @bduderstadt,

I think this is a good rule idea, I created the specification based on your post here https://jira.sonarsource.com/browse/RSPEC-5673

I would be happy if you can provide any feedback on it.

1 Like

Hello @saberduck,

this looks good, thanks a lot for creating the specification.

I noticed a small typo in the proposed message: “intestead” should be “instead”.