Friday 18 March 2011

Annotation approach for DI

Till now we have been seeing the xml approach. This approach was good but now a days, right from spring 2.5 annotations are more preferred. Because now it is felt, that rather than writing so much of xml, its better to put everything in java file as annotations.

Too see more on annotations, please refer this article.

It is argued that somewhere between xml approach and annotation approach, the middle approach is best, where you have some part of both.

Approach 1 : Adding beans to xml file, but getting properties bean by annotation

So @Resource annotation is used for this.

Now consider the FlightRepository class again :

package annotations;

public class FlightRepositoryImpl {

private DataSource dataSource;

@Resource (name="ds")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}


Once putting the annotation on the setter of the method, we have to activate this annotation in the descriptor file using  <context :  annotation-config>.


<import resource="db-config.xml" />
<!--just define that we are using annotation, and flightrepository can refer to this -->
<context:annotation-config />
<bean id="flightRepo" class="annotations.FlightRepositoryImpl" />


Approach 2 : Avoid configuring beans to xml file, doing everything by annotation


Here @Component annotation is used.


Any bean marked by @Component annotation is marked by the IoC container on startup and will be loaded automatically.


To make it more clear spring introduced @Service, @Repository and @Controller stereotypes to distinguish between the same.


Now consider our repository :


package annotations;

@Repository
public class FlightRepositoryImpl {

private DataSource dataSource;
@Resource (name="ds")
public FlightRepositoryImpl2(DataSource dataSource) {
this.dataSource = dataSource;
}
}




Now in the config file we simply add <context:component-scan>.


<import resource="db-config.xml" />
<!-- Needed in the xml file to tell the container about fully annotated components, so it will search in whole package specified, to find all annotations and act accordingly -->
<context:component-scan base-package="annotations" />

 

 





Note that @Resource annotation can be used to inject dependencies by setter or fields.

No comments:

Post a Comment