[Java] Spring IoC Container – autowiring

The thing I want to introduce you is autowiring in Spring IoC Container. Autowiring is the mechanism that allows developer to write less XML code and moves the responsibility for wiring beans to Spring.

I suppose you have read previously article Spring IoC Container – example or know Spring IoC technology.

There are four autowiring modes to set in your bean attribute:

  • no – default option. Autowiring is disabled.
  • byName – beans are wired by names. Spring looks for beans, which names are equal to fields’ names. If more than one matching bean is found (two or more beans with the same name) – following exception is thrown: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Bean name ‘theNameOfBean’ is already used in this element (…). If Spring doesn’t find proper bean – property is not initialized.
  • byType – Spring looks for beans which are the same type as property. If more than exactly one is found – the exception is thrown:
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name (…)
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type (…). If Spring doesn’t find proper bean – property is not initialized as above.
  • constructor – similar to byType. Applies to arguments of contructor. Throws the same exceptions as presented above.

While using autowiring you can also use simple constructor-arg and property injections which overrides autowiring.
Now you have theoretical knowledge, so let’s see the example:



As you see in comparison to example from previous article (Spring IoC Container – example) I introduced autowire attribute and names to wheel beans. The results are the same – you have wired beans and can start using them.

The cons of using autowiring also exists. The XML may be harder to read, you can’t wire primitives, Strings and Classes. So if you want to use it – you have to keep in mind such problems. For me autowiring is a nice feature, which should be used sparingly.

Check also Configuring Spring IoC using @Annotations to see how Spring IoC can be configured 100% programmatically in Java without use any xml.

This entry was posted in coding, enterprise edition, java and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: