Building Microservices with Spring
上QQ阅读APP看书,第一时间看更新

What are Stereotype annotations?

The Spring Framework provides you with some special annotations. These annotations are used to create Spring beans automatically in the application context. The main stereotype annotation is @Component. By using this annotation, Spring provides more Stereotype meta annotations such as @Service, used to create Spring beans at the Service layer, @Repository, which is used to create Spring beans for the repositories at the DAO layer, and @Controller, which is used to create Spring beans at the controller layer. This is depicted in the following diagram:

By using these annotations, Spring creates automatic wiring in these two ways:

  • Component scanning: In this, Spring automatically searches the beans to be created in the Spring IoC container
  • Autowiring: In this, Spring automatically searches the bean dependencies in the Spring IoC container

Implicitly, the DI pattern configuration reduces the verbosity of an application, and minimizes explicit configuration. Let's demonstrate component scanning and autowiring in the same example as discussed previously. Here, Spring will create the beans for TransferService, TransferRepository, and AccountRepository by discovering them, and automatically inject them to each other as per the defined dependencies.