Question 1 – how does Spring IoC container know which beans to create?

We need to tell the Spring IoC container which beans to create. This is done using the @Component annotation. A couple of examples are shown as follows:

    @Component
public class DataServiceImpl implements DataService

@Component
public class BusinessServiceImpl implements BusinessService

When the Spring IoC container sees this annotation in a class, it will create instances of the class. As we discussed earlier, these instances are called beans.

The @Component annotation is the most generic way of defining a Spring bean.

There are other annotations with more specific context associated with them. The @Service annotation is used in business service components. The @Repository annotation is used in the Data Access Object (DAO) components. 

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

    @Repository 
public class DataServiceImpl implements DataService

@Service
public class BusinessServiceImpl implements BusinessService
It is recommended to use specific annotations—@Service and @Repository over the generic @Component annotation because they provide additional features. For example, @Repository provides automatic transaction management in the data layer.
..................Content has been hidden....................

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