Sunday, 1 November 2015

Background

In last post you would have seen what dependency injection is and how is it generally achieved in Spring. It is done using beans that you define in you xml file using tags bean , constructor-arg and property.

But as your project size grows it becomes difficult to keep adding bean in your XML files with its dependencies as the size of xml file continues to grow. So Spring has provided a feature called autowiring where bean dependencies are automatically injected based on various criteria like name, type etc (you can find all types in the previous post). Going a step forward Spring also provides annotations based injection in which case you don't event have to define beans. Spring will scan annotations and inject dependencies on it's own Ofcourse there are rules by which this is governed. We will see this autowiring feature in this post with and without annotations.

Note : Notice the attribute autowire of tag bean which is set to byType. This means Cricket has dependency on Bat instance so find a bean of type Bat and inject into cricket. You can also set it as byName in which case it will match bean name and inject dependency, However be careful in using this - if spring finds two beans of type Bat it will throw exception.

Now run the same program as above and you should again get the same output. Few point to note -

Using @Autowired annotation is same as saying find the bean by type.If Spring finds no bean of injected type for auto-wiring, then it will throw NoSuchBeanDef Exception. If you think that this dependency is not a must than you can use @Autowired(required=false).

As mentioned before @Autowired annotation is similar to autowiting by type. If there are two beans of same type you land in trouble. In such cases you can use resolve by name. For this you can use @Qualifier(value="beanName")

Combination of using @Autowired(required=false) with @Qualifier(value="beanName") is very flexible as you can use this to specify you dependency is not a mandate and you can also specify bean name to resolve with.

Note : If you want to resolve by name then you can use @Resource annotation. Sample usage would be @Resource(name="myBat") . But note here that you loose the flexibility of marking it as non mandatory as you did with @Autowired annotation. All dependencies become mandatory.