Understanding @Autowired vs @Resource and Injection Methods in Spring
The article explains common pitfalls of using Spring's @Autowired, compares it with the standard @Resource annotation, and demonstrates various injection techniques—including field, setter, constructor, and Lombok-based constructor injection—through detailed code examples and best‑practice recommendations.
In this article, a senior architect discusses common pitfalls when using Spring's @Autowired injection, including Java class initialization order and the strong coupling introduced by @Autowired compared to the standard @Resource annotation.
The author explains that @Autowired injection occurs after the subclass constructor, which can lead to NullPointerException if beans are not properly initialized, and highlights that @Resource is a JSR‑250 standard that does not produce warnings, making it more portable across IoC frameworks.
Various injection approaches are presented: field injection using @Autowired , setter injection, constructor injection, and a simplified constructor injection using Lombok's @RequiredArgsConstructor . Code examples for each method are provided.
@RestController
public class TestController2 {
ITestService testService;
/* 基于set注入 */
@Autowired
public void setTestService(ITestService iTestService) {
this.testService = iTestService;
}
@GetMapping("/status2")
public Result
status() {
return testService.status();
}
} @RestController
public class TestController1 {
ITestService testService;
/* 基于构造方法的注入 */
public TestController1(ITestService iTestService) {
this.testService = iTestService;
}
@GetMapping("/status1")
public Result
status() {
return testService.status();
}
} <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency> @RestController
@RequiredArgsConstructor
public class TestController3 {
private final ITestService testService;
@GetMapping("/status3")
public Result
status() {
return testService.status();
}
}Constructor injection is recommended as it avoids circular dependencies and, when combined with Lombok, reduces boilerplate code.
The article concludes that using constructor injection, possibly with Lombok, offers a balanced solution between simplicity and loose coupling.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.