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();
}
}
OutputOrder details, for order id=100
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 4.3.0.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|