Close

Spring - Implicit Constructor Injection In @Configuration Class

[Last Updated: Dec 8, 2020]

Just like in an ordinary bean class, we can also implicitly inject dependency in @Configuration classes (only in Spring 4.3 and later).

Example

package com.logicbig.example;

import org.springframework.stereotype.Component;

@Component
public class Greeter {

  public void greet(String name){
      System.out.println("hi there, "+name);
  }
}

Implicit DI in @Configuration class constructor

package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class AppRunner {
  private Greeter greeter;

  public AppRunner(Greeter greeter) {
      this.greeter = greeter;
  }

  public static void main(String... strings) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppRunner.class);

      AppRunner appRunner = context.getBean(AppRunner.class);
      appRunner.greeter.greet("Joe");
  }
}

Output

hi there, Joe

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.2.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Spring - Constructor bases implicit DI in @Configuration Select All Download
  • spring-implicit-constructor-injection-in-config-class
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AppRunner.java

    See Also