Overview

In this post, we will go through @Component, @Controller, @Repository, @Service annotations in Spring Framework.

Stereotype Annotations

Spring scans and registers Beans in the ApplicationContext. We can use @Component, @Controller, @Repository, @Service depending on the use case.

Let’s see them in detail

@Component
  • @Component is the most generic stereotype for any Spring-managed component which can be used across the applications.
  • It is a class-level annotation and is instantiated by the Spring IoC engine.
@Component
public class TestService {
    public String getData() {
        // logic goes here
    }
}
@Repository
  • @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO).
  • It also activates Persistence exception translation for all beans annotated with @Repository.
  • All unchecked exceptions thrown in class will be converted into Spring’s DataAccessException hierarchy.
  • Basically, @Repository’s job is to catch platform-specific exceptions and re-throw them as one of Spring’s unified unchecked exceptions.
@Repository
public interface MonitorRepository extends JpaRepository<Monitor, String> {
  Monitor findByName(String name);
}
@Service
  • @Service indicates that an annotated class is a “Service” (e.g. a business service facade).
  • It currently doesn’t provide any additional behavior over the @Component annotation.
@Service
@RequiredArgsConstructor
public class EmailService {

    private final JavaMailSender emailSender;
    
    public void sendSimpleMessage(String to, String subject, String text) {
        //logic goes here
    }
}
@Controller
  • @Controller is a stereotype for the presentation layer (spring-mvc)
  • Dispatcher will scan these annotated classes for mapped methods, detecting @RequestMapping annotations.
@Controller
@RequestMapping("/view/")
public class ViewController {
 
    @RequestMapping("test")
    public ModelAndView getView(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		//logic goes here 
   }
}

Fun Fact

  • Spring’s component-scan only scans @Component and doesn’t look for @Controller, @Service and @Repository directly. They are scanned because they are annotated with @Component.
  • We cannot switch @Controller with any others like @Service or @Repository, as dispatcher scans @RequestMapping and they will work inside class annotated with @Controller only.

Conclusion

In this post we saw different variant of @Component – @Controller, @Repository, @Service


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *