Jeetu Alex - IT Software Professional specialized in developing high-end, customized business solutions using Coldfusion and Java.

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more...

Tuesday, October 22, 2013

Spring Bean Auto wiring

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.

 

The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:

  • no: This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.

  • byName: Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

  • byType: Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.

  • constructor: Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

  • autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

  •  

    Limitations of autowiring are:

  • Overriding possibility: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.

  • Primitive data types: You cannot autowire so-called simple properties such as primitives, Strings, and Classes.

  • Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

  •  

    Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.

     

    Note: null and empty string values can be injected in Spring