Spring Beans Autowiring Example (original) (raw)

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.

1. Introduction

1.1 Spring Framework

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:

Always remember, in the XML based configuration; the autowire functionality is enabled by defining the autowire attribute i.e.

1.2.1 Autowiring modes in spring

Spring framework provides four major flavors of the autowiring modes. They are:

Below snippet shows how to configure the byType autowiring mode:
Code Snippet

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!

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!

Spring Beans Autowiring - Application Project Structure

Fig. 1: Application Project Structure

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.

Spring Beans Autowiring - Create a Maven Project

Fig. 2: Create a 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.

Spring Beans Autowiring - Project Details

Fig. 3: Project Details

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.

Spring Beans Autowiring - Archetype Parameters

Fig. 4: Archetype Parameters

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

4.0.0 com.spring SpringBeansAutowiring 0.0.1-SNAPSHOT jar

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

4.0.0 com.spring SpringBeansAutowiring 0.0.1-SNAPSHOT Spring Beans Autowiring Example org.springframework spring-beans 5.0.8.RELEASE org.springframework spring-context 5.0.8.RELEASE ${project.artifactId} </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

<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>

3.3.2 Autowiring byType

A typical bean configuration file for the autowire=byType will look like this:

autowire_byType.xml

<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>

3.3.3 Autowiring byName

A typical bean configuration file for the autowire=byName will look like this:

autowire_byName.xml

<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>

3.3.4 Constructor Autowiring

A typical bean configuration file for the autowire=constructor will look like this:

autowire_constructor.xml

<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>

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!

Spring Beans Autowiring - Run the Application

Fig. 5: Run the Application

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.

Spring Bean Autowiring

Fig. 6: Spring Bean Autowiring

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.

Download
You can download the full source code of this example here: SpringBeansAutowiring

Photo of Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).