Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection

We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in the bean-config file (applicationContext.xml).

Need for autowiring by Constructor Injection

If more than one constructor or bean is available for dependency injection, it creates a lot of confusion inside the bean-config file. To reduce the lines of code in the bean-config file, we are using the annotation-based Constructor Dependency Injection (CDI). It is also known as Auto-wiring by CDI.

To create an example of Constructor Dependency Injection using auto-wiring, we use the following annotations:

@Component - We have discussed @Component annotation in our previous tutorials. It is used to create a class as a component.

@Autowired - The @Autowired annotation is used to inject the dependencies automatically.

Example of Autowiring using Constructor Injection

In this example, we have created an interface and the component class. The Fortune.java and Coach.java are the interfaces that consist of the unimplemented methods. The GoodLuckFortune.java and Cricket_Coach.java are two Component classes that implement the Fortune.java and Coach.java, respectively.

Following are the steps to create an example of CDI using @Autowired:

Fortune.java

public interface Fortune {
public String fortuneService();
} 

GoodLuckFortune.java

import org.springframework.stereotype.Component;
@Component
public class GoodLuckFortune implements Fortune{
public String fortuneService() {
return "Goodluck for Today..!!";
}
} 

Coach.java

public interface Coach {
public String workout();
public String getDailyFortune();
} 

Cricket_Coach.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Cricket_Coach implements Coach {
private Fortune fortuneservice;
@Autowired
public Cricket_Coach(Fortune fortuneservice) { 
super();
this.fortuneservice = fortuneservice;
}
public String workout() {
return "daily 1 hour of running ";
}
public String getDailyFortune() {
return fortuneservice.fortuneService(); 
}
} 

In the above code, we have defined the @Autowired annotation just above the constructor as we are doing the Constructor Dependency Injection.

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

 

App.java

import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class App 
 {
public static void main( String[] args )
{
ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
Coach co = appcontext.getBean("cricket_Coach", Coach.class); 
System.out.println("Autowiring Dependency Injection using Constructor:" + co.workout());
System.out.println("Autowiring Dependency Injection using Constructor: " + co.getDailyFortune());
appcontext.close();
}
} 

OUTPUT

applicationContext.xml


Related Topics

Spring AOP – @AfterReturning Advice

Spring AOP – @AfterReturning Advice We have discussed earlier the types of advices available in Spring AOP. One of them is After Returning advice. It is an advice that executes after the normal execution...

3 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

Spring AOP – Pointcut Expressions

Spring AOP – Pointcut Expressions Pointcut refers to a collection of join points that specify where advice to be applied. In other words, pointcut represents a set of various join points. It defines that...

7 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring MVC – @RequestParam

We have already discussed an example of Spring MVC in our previous tutorials. Here, we are going to discuss the @RequestParam annotation. In the last case, we had created a bean class for...

8 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.

Spring Autowiring – Setter Injection

Spring Autowiring – Setter Injection We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency...

2 minutes read.

Spring - Bean Scopes with Annotations

Spring - Bean Scopes with Annotations We have previously discussed the Spring bean scopes using an XML-based configuration. In the XML-based configuration, we have defined the beans and its scope inside the bean-config...

3 minutes read.

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring MVC Form Validation

Spring Validation is used to validate the @Controller inputs. It is used to check and accept the user input in any web application. Using Spring validation, we can validate the user input on...

12 minutes read.

Spring MVC Form Tag Library

The Spring MVC provides a variety of tags available in the form of a tag library, which is used to develop web pages (JSP view pages). The Spring’s form tag...

6 minutes read.

Spring Autowiring

Spring Autowiring Autowiring is an essential feature of the Spring framework. The autowiring function is used for wiring beans automatically, without injecting the beans using <constructor-arg> and <property> elements in the bean-config file. It can...

3 minutes read.

Spring Autowiring –Field Injection

Spring Autowiring –Field Injection The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a...

2 minutes read.

Spring - Injecting values from Property Files

Spring - Injecting values from Property Files In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource...

3 minutes read.

Spring MVC Number Range Validation

Example of Number Range Validation Here, we are going to create an example of number range validation. Following are the steps to create an example of number range validation. Create a request page In this step, we are...

12 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.

Spring AOP - @AfterThrowing Advice

Spring AOP - @AfterThrowing Advice As we have discussed in our previous tutorial, Advice is one of the essential concepts of the Spring AOP. The after throwing advice is one of the types of...

3 minutes read.

Spring – Bean Lifecycle

Spring – Bean Lifecycle Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires...

4 minutes read.