Bean declaration

First of all, let's take a look at how to use Spring annotations to declare beans. 

Spring provides a set of stereotype annotations for declaring beans, including @Component, @Service, @Controller, and @Repository. We can apply these annotations to the classes that need to be managed by Spring. And Spring will pick them up by scanning the packages, starting from the base package that we provide to the @ComponentScan annotation.

The @Component annotation is a generic stereotype. When a class is annotated with this annotation, Spring will instantiate an instance of that class. The @Service annotation is a specialization of @Component, and it indicates that the annotated class is a service, a term used in Domain-Driven Design (Evan, 2003), or a business service façade, a pattern in the Core J2EE. The @Repository annotation indicates that a component is a repository, also, a term used in Domain-Driven Design, or Data Access Object (DAO), a traditional Java EE pattern. The @Controller annotation indicates that a component is a web controller that can accept HTTP requests. We will talk more about @Service, @Repository, and @Controller later. For now, let's simply use the @Component annotation. The following is the change made to MessageService:

...
import org.springframework.stereotype.Component;
@Component
public class MessageService {
...

As you can see, in order to have our beans managed by Spring, all we need to do is to apply the @Component annotation at the class-level. The following is the change made to MessageRepository:

...
import org.springframework.stereotype.Component;
@Component
public class MessageRepository {
...

And since we have already used @Component to declare beans of MessageService and MessageRepository, let's delete the messageRepository() and messageService() methods from AppConfig, since they are no longer required.

As a matter of fact, if we leave these two methods in AppConfig, Spring will still use them to create instances of MessageRepository and MessageService, and the @Component annotation applied to these two classes won't take effect. They are overridden by the @Bean annotation inside AppConfig.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.204.5