Flat Preloader Icon

Dependency Injection by Constructor

  • Dependency Injection (DI) by constructor is a popular and recommended approach in Spring for providing dependencies to a class when it’s instantiated. This form of dependency injection involves passing dependencies (usually other objects or services) into a class’s constructor.
Here’s a step-by-step explanation of how Dependency Injection by constructor works in the context of Spring

Dependency Definition:

  • In your Spring application, you define the components (beans) that you want to use and configure their dependencies. These components can represent various parts of your application, such as services, DAOs, or controllers.

Constructor Definition:

  • Within your Java class, you define a constructor that accepts one or more parameters. These parameters represent the dependencies that the class needs to function correctly. Each parameter should have a corresponding instance variable in the class to store the injected dependency.
				
					public class MyService {
    private DependencyA dependencyA;
    private DependencyB dependencyB;

    public MyService(DependencyA dependencyA,
    DependencyB dependencyB) {
        this.dependencyA = dependencyA;
        this.dependencyB = dependencyB;
    }

    // Other methods of MyService that
    use dependencyA and dependencyB
}

				
			

Spring Configuration:

  • In your Spring configuration (whether using XML, Java-based configuration, or annotations), you define the beans for your classes, including specifying the dependencies they require. Spring will automatically handle the injection of these dependencies.
				
					@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService(dependencyA(),
        dependencyB());
    }

    @Bean
    public DependencyA dependencyA() {
        return new DependencyA();
    }

    @Bean
    public DependencyB dependencyB() {
        return new DependencyB();
    }
}

				
			

Injection Process:

  • When the Spring IoC (Inversion of Control) container initializes your beans, it detects the constructor with dependencies in your class. Spring then looks for beans in the container that match these dependencies and injects them automatically when creating instances of your class.

Usage:

  • Your application code can now use the MyService bean without worrying about creating or managing its dependencies explicitly. Spring takes care of providing the required dependencies at runtime.
				
					public class MainApplication {
    public static void main(String[] args) {
        ApplicationContext context
= new AnnotationConfigApplicationContext
        (AppConfig.class);

        MyService myService = context
        .getBean(MyService.class);
// Use myService, which has its dependencies
        injected
    }
}

				
			

Injecting primitive and string-based values

  • In Spring, you can inject not only objects and beans but also primitive values and String-based values into your Spring beans. This is useful when you need to configure properties, constants, or other simple values in your application. There are several ways to inject these values into your Spring beans

Using XML Configuration:

  • If you’re using XML-based configuration in Spring, you can use the element to inject primitive and String values.
				
					<bean id="myBean" class="com.example.MyBean">
<property name="integerValue" value="42" />
<property name="stringValue" value
    ="Hello, Spring!" />
</bean>

				
			
  • In the Java class, define setter methods for the properties you want to inject:
				
					public class MyBean {
    private int integerValue;
    private String stringValue;

    // Setter methods for the properties
   public void setIntegerValue
   (int integerValue) {
        this.integerValue = integerValue;
    }

public void setStringValue
(String stringValue)
{
        this.stringValue = stringValue;
    }
}

				
			

Using Java Configuration:

  • If you’re using Java-based configuration, you can use the @Value annotation to inject values directly into fields or constructor parameters.
				
					@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean
        (42, "Hello, Spring!");
    }
}

				
			
  • In the Java class, you can use the @Value annotation to inject values:
				
					public class MyBean {
    private int integerValue;
    private String stringValue;

    public MyBean(@Value("42") 
    int integerValue,
    @Value("Hello, Spring!") 
    String stringValue) {
        this.integerValue
        = integerValue;
        this.stringValue = stringValue;
    }
}

				
			

Using Property Placeholder Configuration:

  • Spring allows you to externalize configuration properties into a properties file and then inject those values into your beans using placeholders. First, define a properties file (e.g., application.properties) with your values:
				
					mybean.integerValue=42
mybean.stringValue=Hello, Spring!

				
			
  • Then, configure your Spring application to use property placeholders:
				
					<context:property-placeholder location
="classpath:application.properties" />

				
			
  • Finally, inject the values into your beans:
				
					<bean id="myBean"
class="com.example.MyBean">
    <property name="integerValue" value
    ="${mybean.integerValue}" />
    <property name="stringValue" value
    ="${mybean.stringValue}" />
</bean>