Spring 2.5 – Heavily Auto-Wired

Concept to auto-wire relationships among spring enabled beans has always been there. The idea with auto-wiring is to get away from the tedious task of specifying and more importantly maintaining explicit wiring. Originally it was supported to be done by name, by type, by constructors or auto-detect and then you had the option to auto-wire all or specific beans within a context. But now with Spring 2.5 the auto wiring concept has taken a whole new meaning and so is the debate if we really want to do auto-wiring.

 

Spring 2.5 has a new @Autowire annotation. @Autowire annotation let us do much fine grained auto-wiring then was possible before and also it make it much more explicit and safer then was possible in pre Spring 2.5 times

 

 

Lets consider few examples

#1

@Autowired

public void init(AccountDao accountDao, CustomerDao customerDao) {

this.accountDao = accountDao;

this.customerDao = customerDao;

}

Do not need to have setters with one parameter to inject dependencies, any method with any name and any number of parameters will do. Can be applied to fields and constructors as well and obviously to the favorite setters :)

 

#2

@Autowired

private BaseDao[] daos;

or

@Autowired

private Set<BaseDao> daos;

Create an array or collection with all the possible beans available in the context..

 

#3

@Autowired(required=false)

private AccountDao accountDao = new AccountDao();

Find it do it, if not leave it.

 

 

Moving on we can even fine control this by using another annotation @Qualifier. Again lets see some more examples

#4

@Autowired

@Qualifier(“bankService”)

private BankService bkService;

We are doing by-name auto-wiring by providing a bean name within the annotation. This might help by letting you declare the name of the property different from the name of the bean.

 

#5 – Example of custom qualifier annotations to take care of the case when we have more then one implementation which we want to auto-wire

Define an annotation like this

@Target({ElementType.FIELD, ElementType.PARAMETER})

@Retention(RetentionPolicy.RUNTIME)

@Qualifier

public @interface Category {

String value();

}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.