Tuesday, 11 September 2018

Spring Auto-Wiring Beans with @Autowired annotation in Constructor | Spring @Autowired Annotation

Master Spring & Java Development!

Subscribe to Ram N Java for clean, beginner-friendly coding guides!

🔔 Subscribe to Ram N Java

Overview: Constructor Injection with @Autowired

In the Spring Framework, Dependency Injection (DI) is the core design pattern used to build modular and testable applications. While Spring supports field and setter injection, Constructor Injection is widely regarded as the industry best practice. Using the @Autowired annotation on constructors allows Spring to resolve and inject required dependencies at the exact moment a bean is instantiated.

In this guide, you will learn how constructor-based dependency injection works using @Autowired, its architectural advantages, and how to implement it in your Spring applications.

Why Choose Constructor Injection?

Constructor injection offers several critical benefits for enterprise Java applications:

  • Immutability: Dependencies can be declared as final, ensuring that once initialized, they cannot be modified or reassigned.
  • Guaranteed Initialization: The bean cannot be instantiated in an incomplete or partially initialized state without its mandatory dependencies.
  • Effortless Unit Testing: Since dependencies are passed via the constructor, you can easily mock or instantiate classes in plain unit tests without starting a full Spring container.
  • Clear Dependency Contracts: The constructor explicitly documents every required collaborator directly in the class signature.

Step-by-Step Implementation

  1. Define the Collaborator Bean: Create the component to be injected and register it within the Spring container (e.g., using @Component or XML).
  2. Annotate the Constructor: Add the @Autowired annotation to the target class constructor:
    @Autowired
    public OrderService(PaymentService paymentService) {
      this.paymentService = paymentService;
    }
  3. Run the Spring Application: When the ApplicationContext initializes, Spring locates the matching bean by type and passes it into the constructor.

Recommended Next Videos from Ram N Java


Click here to watch on Youtube:
https://www.youtube.com/watch?v=deAqXjCpTDM&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:
Spring Auto-Wiring Beans with @Autowired annotation in Constructor | Spring @Autowired Annotation

Spring Auto-Wiring Beans with @Autowired annotation in Constructor | Spring @Autowired Annotation

Spring Auto-Wiring Beans with @Autowired annotation in Constructor | Spring @Autowired Annotation


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%20http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ram.core</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringDemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 5 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</project>

Address.java

package com.ram.model;

public class Address
{
    private String city;
    private String state;
    private String country;

    public Address(String city, String state, String country)
    {
        this.city = city;
        this.state = state;
        this.country = country;
    }

    @Override
    public String toString()
    {
        return "Address [city=" + city + ", state=" + state + ", country="
                + country + "]";
    }

}

Employee.java

package com.ram.model;

import org.springframework.beans.factory.annotation.Autowired;

public class Employee
{
    private String name;
    private Address address;

    @Autowired
    public Employee(String name, Address address)
    {
        System.out.println("Employee(String name, Address address) constructor "
                + "is called by the Spring container");
        this.name = name;
        this.address = address;
    }

    public void displayEmployeeDetails()
    {
        System.out.println(
                "Employee [name=" + name + ", address=" + address + "]");
    }

}

applicationContext.xml

<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-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">


    <context:annotation-config />

    <bean id="address" class="com.ram.model.Address">
        <constructor-arg value="Chennai"></constructor-arg>
        <constructor-arg value="Tamil Nadu"></constructor-arg>
        <constructor-arg value="India"></constructor-arg>
    </bean>

    <bean id="employee" class="com.ram.model.Employee">
        <constructor-arg value="Peter"></constructor-arg>
    </bean>

</beans>


App.java

package com.ram.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.model.Employee;

public class App
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        System.out.println("---------------------------------------");

        Employee employee = (Employee) context.getBean("employee");
        System.out.println(
                "Got employee object from the ApplicationContext[Spring Container]");
       
        employee.displayEmployeeDetails();
    }

}

Output

Aug 19, 2018 10:30:53 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5b37e0d2: startup date [Sun Aug 19 10:30:53 IST 2018]; root of context hierarchy
Aug 19, 2018 10:30:53 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Employee(String name, Address address) constructor is called by the Spring container
---------------------------------------
Got employee object from the ApplicationContext[Spring Container]
Employee [name=Peter, address=Address [city=Chennai, state=Tamil Nadu, country=India]]


Click the below link to download the code:
https://sites.google.com/site/ramj2eev2/java_basics/SpringDemo_Autowired_Cons.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/javaee/tree/master/Spring_2018/SpringDemo_Autowired_Cons

Bitbucket Link:
https://bitbucket.org/ramram43210/spring/src/0983b6309d20dda573f6ff9d78abf50ca4f8465a/Spring_2018/SpringDemo_Autowired_Cons/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • 1 comment:

    1. It is really a nice and helpful piece of information. I’m glad that you shared this useful information with us. Please visit my web site beansroasterykw.com. Best Best Coffee Beans In Kuwait service provider.

      ReplyDelete

    Tutorials