« Previous | 1 | 2 | 3 | Next »

Spring – Beans Autowiring


You have learnt how to declare beans using the <bean> element and inject <bean> using <constructor-arg> and <property> elements in XML configuration file.

The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements, which helps cut down on the amount of XML configuration you write for a big Spring-based application.

Autowiring Modes

Following are the autowiring modes, which can be used to instruct the Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition.
ModeDescription
noThis is a default setting which means no autowiring and you should use explicit bean reference for wiring. You have to do nothing special for this wiring. This is what you already have seen in Dependency Injection chapter.
byNameAutowiring 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.
byTypeAutowiring 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 the configuration file. If more than one such beans exists, a fatal exception is thrown.
constructorSimilar to byType, but this 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.
autodetectSpring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
Autowiring ‘byName’

This mode specifies autowiring by property name. Spring container looks at the beans on which auto-wire 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. If matches are found, it will inject those beans. Otherwise, it will throw exceptions.

For example, if a bean definition is set to autowire byName in the configuration file, and it contains a spellChecker property (that is, it has a setSpellChecker(...)method), Spring looks for a bean definition named spellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept.

Let us have a working Eclipse IDE in place and take the following steps to create a Spring application:
StepsDescription
1Create a project with a name SpringExample and create a packagecom.jtc under the src folder in the created project.
2Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3Create Java classes TextEditor, SpellChecker and MainApp under thecom.jtc package.
4Create Beans configuration file Beans.xml under the src folder.
5The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
Here is the content of TextEditor.java/b> file

package com.jtc;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}

Following is the content of another dependent class file SpellChecker.java

package com.jtc;
public class SpellChecker {
public SpellChecker() {
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}

Following is the content of the MainApp.java file:

package com.jtc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}

Following is the configuration file Beans.xml in a normal condition

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.jtc.TextEditor">
<property name="spellChecker" ref="spellChecker" />
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.jtc.SpellChecker">
</bean>
</beans>

But if you are going to use autowiring 'byName', then your XML configuration file will become as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.jtc.TextEditor"
autowire="byName">
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.jtc.SpellChecker">
</bean>
</beans>

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message:

Inside SpellChecker constructor.
Inside checkSpelling.

Autowiring ‘byType’

This mode specifies autowiring by property type. Spring container looks at 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 the configuration file. If matches are found, it will inject those beans. Otherwise, it will throw exceptions.

For example, if a bean definition is set to autowire byType in the configuration file, and it contains a spellChecker property of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept where you will find no difference with the above example except XML configuration file has been changed.

Let us have a working Eclipse IDE in place and take the following steps to create a Spring application:
StepsDescription
1Create a project with a name SpringExample and create a packagecom.jtc under the src folder in the created project.
2Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3Create Java classes TextEditor, SpellChecker and MainApp under thecom.jtc package.
4Create Beans configuration file Beans.xml under the src folder.
5The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
Here is the content of TextEditor.java file

package com.jtc;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public void setSpellChecker( SpellChecker spellChecker ) {
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}

Following is the content of another dependent class file SpellChecker.java

package com.jtc;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}

Following is the content of the MainApp.java file

package com.jtc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}

Following is the configuration file Beans.xml in a normal condition:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.jtc.TextEditor">
<property name="spellChecker" ref="spellChecker" />
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.jtc.SpellChecker">
</bean>
</beans>

But if you are going to use autowiring 'byType', then your XML configuration file will become as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.jtc.TextEditor"
autowire="byType">
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="com.jtc.SpellChecker">
</bean>
</beans>

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message:

Inside SpellChecker constructor.
Inside checkSpelling.

Autowiring by Constructor

This mode is very similar to byType, but it applies to constructor arguments. Spring container looks at the beans on which autowire attribute is set toconstructor in the XML configuration file. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, it will throw exceptions.

For example, if a bean definition is set to autowire by constructor in the configuration file, and it has a constructor with one of the arguments ofSpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the constructor's argument. Still you can wire the remaining arguments using <constructor-arg> tags. The following example will illustrate the concept.

Let us have a working Eclipse IDE in place and take the following steps to create a Spring application:
StepsDescription
1Create a project with a name SpringExample and create a packagecom.jtc under the src folder in the created project.
2Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3Create Java classes TextEditor, SpellChecker and MainApp under thecom.jtc package.
4Create Beans configuration file Beans.xml under the src folder.
5The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
Here is the content of TextEditor.java file

package com.jtc;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public TextEditor( SpellChecker spellChecker, String name ) {
this.spellChecker = spellChecker;
this.name = name;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}

Following is the content of another dependent class file SpellChecker.java

package com.jtc;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling()
{
System.out.println("Inside checkSpelling." );
}
}

Following is the content of the MainApp.java file

package com.jtc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}

Following is the configuration file Beans.xml in a normal condition

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.jtc.TextEditor">
<constructor-arg ref="spellChecker" />
<constructor-arg value="Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.jtc.SpellChecker">
</bean>
</beans>

But if you are going to use autowiring 'by constructor', then your XML configuration file will become as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.jtc.TextEditor"
autowire="constructor">
<constructor-arg value="Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="com.jtc.SpellChecker">
</bean>
</beans>

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message:

Inside SpellChecker constructor.
Inside checkSpelling.

You can use byType or constructor autowiring mode to wire arrays and other typedcollections.

Limitations with Autowiring

Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and disadvantages of autowiring before using them.

LimitationsDescription
Overriding possibilityYou can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
Primitive data typesYou cannot autowire so-called simple properties such as primitives, Strings, and Classes.
Confusing natureAutowiring is less exact than explicit wiring, so if possible prefer using explict wiring.
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com