Spring Beans Autowiring Example
One of the most important development principles of the modern software design is the ability to autowire the relationships between the collaborating beans. Spring framework provides a mechanism to implicitly inject the object dependencies.
In spring, developers can implement the autowiring functionality with the traditionally XML based or the annotation based configuration. This tutorial will explore the different auto-wiring modes with an XML based configuration in the spring framework.
Table Of Contents
1. Introduction
1.1 Spring Framework
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring Bean Autowiring
The autowiring feature of the spring framework enables the developers to automatically inject the object dependencies into the associated references of a pojo class. Spring autowiring feature:
- Internally uses the setter or the constructor dependency injection
- Can’t be used to inject the primitive values and works only with the reference objects
Always remember, in the XML based configuration; the autowire functionality is enabled by defining the autowire
attribute i.e.
<bean id="bean_id" class="bean_class" autowire="default | byname | byType | constructor | autodetect " />
1.2.1 Autowiring modes in spring
Spring framework provides four major flavors of the autowiring modes. They are:
no
: This is the default autowiring mode in spring and it means that autowiring will not be performed. Below three code snippets shows how to configure theno
or thedefault
autowiring mode:
Code Snippet<bean id="bean_id" class="bean_class" autowire="default" /> <bean id="bean_id" class="bean_class" autowire="no" /> <bean id="bean_id" class="bean_class" />
In this case, developers will have to explicitly set the object dependencies via the
<ref />
attributebyName
: Autowire by property name i.e. this mode injects the object dependency according to the bean name. Container examines the spring configuration file for the bean having the id or the name attribute same as the property name.- This autowiring mode is applied to the setter methods
- There is no chance of an exception as multiple beans in the spring configuration file cannot have a same value of the id attribute
- In case the bean with the given id or name does not exist, that property will remain unset and it may later result in an exception
Below snippet shows how to configure the
byName
autowiring mode:Code Snippet
<bean id="bean_id" class="bean_class" autowire="byName" />
byType
: Autowire by property type i.e. this mode injects the object dependency based on the data-type of the property name. Container examines the spring configuration file for the bean having the same class type.- This autowiring mode is applied to the setter methods
- If no bean with the class type is found then the property will remain unset
- If a single bean with the class type is found then the property will be set
- If multiple beans of the same class type are found in the configuration file, then an
UnsatisfiedDependencyException
will be thrown. To solve this problem there are two options i.e.- Identify a primary candidate for the autowiring bean and set that as primary using the
primary="true"
attribute i.e.<bean id="bean_id" class="bean_class" primary="true" />
- Exclude a bean from being autowired by setting the
<autowired-candidate />
attribute of the<bean />
tag tofalse
i.e.<bean id="bean_id" class="bean_class" autowire-candidate="false" />
- Identify a primary candidate for the autowiring bean and set that as primary using the
Below snippet shows how to configure the
byType
autowiring mode:Code Snippet
<bean id="bean_id" class="bean_class" autowire="byType" />
constructor
: This mode is similar tobyType
but applies to the arguments of a constructor. In autowired enabled bean, the container will look for the class type of the constructor arguments, and then do an autowirebyType
on all the constructor arguments. Below snippet shows how to configure theconstructor
autowiring mode:
Code Snippet<bean id="bean_id" class="bean_class" autowire="constructor" />
Note: As per Spring 4.x, the autodetect
autowiring mode has been removed.
Now, open up the Eclipse IDE and let’s see how to implement the different auto-wiring modes in the spring framework!
2. Spring Beans Autowiring Example
Here is a step-by-step guide for implementing this tutorial in the spring framework.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8, MySQL and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring</groupId> <artifactId>SpringBeansAutowiring</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> </project>
We can start adding the dependencies that developers want like Spring Core, Spring Context etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the spring framework. The rest dependencies such as Spring Beans, Spring Core etc. will be automatically resolved by Maven. The updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring</groupId> <artifactId>SpringBeansAutowiring</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Spring Beans Autowiring Example</name> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.8.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.8.RELEASE</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project
3.2 Java Class Creation
Let’s write the Java classes involved in this application.
3.2.1 Implementation of Driver Model
This POJO class contains the three fields for demonstrating the default autowiring, autowiring byType, and autowiring byName. Add the following code to it:
Driver.java
package com.spring.pojo; public class Driver { private String name; private String age; private Licence licence; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Licence getLicence() { return licence; } public void setLicence(Licence licence) { this.licence = licence; } @Override public String toString() { return "Driver [name=" + name + ", age=" + age + ", licence=" + licence.toString() + "]"; } }
3.2.2 Implementation of Driver2 Model
This POJO class contains the three fields for demonstrating the constructor autowiring. Add the following code to it:
Driver2.java
package com.spring.pojo; public class Driver2 { private String name; private String age; private Licence licence; public Driver2() { } public Driver2(String dname, String dage, Licence dlicence) { this.name = dname; this.age = dage; this.licence = dlicence; } @Override public String toString() { return "Driver2 [name=" + name + ", age=" + age + ", licence=" + licence.toString() + "]"; } }
3.2.3 Implementation of Licence Model
This POJO class contains a single field for demonstrating the different autowiring types in the spring framework. Add the following code to it:
Licence.java
package com.spring.pojo; public class Licence { private String number; public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Override public String toString() { return "Licence [number=" + number + "]"; } }
3.2.4 Implementation of Utility Class
The implementation class will get the bean definition from the context file and performs the particular type of autowiring. Add the following code to it:
AppMain.java
package com.spring.impl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.pojo.Driver; import com.spring.pojo.Driver2; public class AppMain { @SuppressWarnings("resource") private static void autowireMode(String filename) { ApplicationContext ac = new ClassPathXmlApplicationContext(filename); if (filename.equalsIgnoreCase("autowire_constructor.xml")) { Driver2 driver2 = ac.getBean("mydriver", Driver2.class); System.out.println("Details are= " + driver2.toString()); } else { Driver driver = ac.getBean("mydriver", Driver.class); System.out.println("Details are= " + driver.toString()); } } public static void main(String[] args) { int choice = Menu.displayMenu(); switch (choice) { case 1: System.out.println("'Autowire - no' selected"); autowireMode("autowire_default.xml"); break; case 2: System.out.println("'Autowire - byType' selected"); autowireMode("autowire_byType.xml"); break; case 3: System.out.println("'Autowire - byName' selected"); autowireMode("autowire_byName.xml"); break; case 4: System.out.println("'Autowire - constructor' selected"); autowireMode("autowire_constructor.xml"); break; default: System.err.println("Invalid choice."); } } }
3.3 Configuration Files
Let’s write all the configuration files involved in this application.
3.3.1 Default Autowiring
A typical bean configuration file for the autowire=no
will look like this:
autowire_default.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="mylicence" class="com.spring.pojo.Licence"> <property name="number" value="CXRMM7RS" /> </bean> <!-- default example (autowire="no") --> <bean id="mydriver" class="com.spring.pojo.Driver" autowire="no"> <property name="name" value="Daniel" /> <property name="age" value="29" /> <property name="licence" ref="mylicence" /> </bean> </beans>
3.3.2 Autowiring byType
A typical bean configuration file for the autowire=byType
will look like this:
autowire_byType.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="mylicence" class="com.spring.pojo.Licence"> <property name="number" value="5MNAQ5VV" /> </bean> <!-- byType example --> <bean id="mydriver" class="com.spring.pojo.Driver" autowire="byType"> <property name="name" value="Charlotte" /> <property name="age" value="27" /> </bean> </beans>
- In the configuration file, there is a bean of type
Licence
which matches the type of thelicence
field in theDriver.java
class. Thus autowiring byType will work
3.3.3 Autowiring byName
A typical bean configuration file for the autowire=byName
will look like this:
autowire_byName.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="licence" class="com.spring.pojo.Licence"> <property name="number" value="WUL9TS2C" /> </bean> <!-- byName example --> <bean id="mydriver" class="com.spring.pojo.Driver" autowire="byName"> <property name="name" value="Jane" /> <property name="age" value="28" /> </bean> </beans>
- In this case, spring will see that the
Driver.java
class has one property named aslicence
. Thus spring framework will match for the bean with same name or id in the configuration file
3.3.4 Constructor Autowiring
A typical bean configuration file for the autowire=constructor
will look like this:
autowire_constructor.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="mylicence" class="com.spring.pojo.Licence"> <property name="number" value="ZPMKFLB8" /> </bean> <!-- constructor example --> <bean id="mydriver" class="com.spring.pojo.Driver2" autowire="constructor"> <constructor-arg index="0" value="Kurt" /> <constructor-arg index="1" value="31" /> </bean> </beans>
4. Run the Application
To execute the application, right click on the AppMain
class, Run As -> Java Application
. Developers can debug the example and see what happens after every step. Enjoy!
5. Project Demo
The code shows the Bean Autowiring menu as shown in Fig. 6. Users can select the particular option to briefly understand the different autowiring concepts in spring framework.
That’s all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and don’t forget to share!
6. Conclusion
This post defines the different bean autowiring scopes in the spring framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of Spring Beans Autowiring for beginners.
You can download the full source code of this example here: SpringBeansAutowiring