Close

Spring - Implicit constructor Injection

[Last Updated: Dec 7, 2020]

Starting Spring 4.3, it is no longer necessary to specify the @Autowired annotation for constructor based dependency injection.


As we saw in different ways of DI example project, that we had to use @Autowired on the constructor when using @ComponentScan. Starting Spring 4.3, @Autowired is no longer required on constructor.


Example

package com.logicbig.example;

import org.springframework.stereotype.Component;

@Component
public class OrderService {

  public String getOrderDetails(String orderId) {
      return "Order details, for order id=" + orderId;
  }
}

Performing constructor base DI without @Autowired

package com.logicbig.example;

import org.springframework.stereotype.Component;

@Component
public class OrderServiceClient {

  private OrderService orderService;

  //@Autowired is no longer required in Spring 4.3 and later.
  public OrderServiceClient(OrderService orderService) {
      this.orderService = orderService;
  }

  public void showPendingOrderDetails () {
      System.out.println(orderService.getOrderDetails("100"));
  }
}

Configuration class and running the example

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 {

  public static void main(String... strings) {
      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppRunner.class);
      OrderServiceClient bean = context.getBean(OrderServiceClient.class);
      bean.showPendingOrderDetails();
  }
}

Output

Order details, for order id=100

Example Project

Dependencies and Technologies Used:

  • Spring Context 4.3.2.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Spring - Implicit constructor Injection Select All Download
  • spring-implicit-constructor-injection
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • OrderServiceClient.java

    See Also