Mastering Spring 5.0
上QQ阅读APP看书,第一时间看更新

Defining beans and wiring

Let's address the first question; how does the Spring IoC container know which beans to create?

We need to tell the Spring IoC container which beans to create. This can be done using @Repository or @Component or @Service annotations on the classes for which beans have to be created. All these annotations tell the Spring Framework to create beans for the specific classes where these annotations are defined.

A @Component annotation is the most generic way of defining a Spring bean. Other annotations have more specific context associated with them. @Service annotation is used in business service components. @Repository annotation is used in Data Access Object (DAO) components.

We use @Repository annotation on DataServiceImpl because it is related to getting data from the database. We use @Service annotation on the BusinessServiceImpl class as follows, since it is a business service:

    @Repository 
public class DataServiceImpl implements DataService
@Service
public class BusinessServiceImpl implements BusinessService

Let's shift our attention to question 2 now--how does the Spring IoC container know how to wire beans together? The bean of the DataServiceImpl class needs to be injected into that of the BusinessServiceImpl class.

We can do that by specifying an @Autowired annotation on the instance variable of the DataService interface in the BusinessServiceImpl class:

    public class BusinessServiceImpl { 
@Autowired
private DataService dataService;

Now that we have defined the beans and their wiring, to test this, we need an implementation of DataService. We will create a simple, hardcoded implementation. DataServiceImpl returns a couple of pieces of data:

    @Repository 
public class DataServiceImpl implements DataService {
public List<Data> retrieveData(User user) {
return Arrays.asList(new Data(10), new Data(20));
}
}

Now that we have our beans and dependencies defined, let's focus on how to create and run a Spring IoC container.