Spring构造器方式注入bean
需要注入的类要用final修饰
1. 构造器方式注入bean
@RestController
@RequestMapping("/test")
public class TestController {
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
@GetMapping("/testAsync")
public String testAsync(){
return testService.asyncMethod();
}
}
2. 使用lombok的@RequiredArgsConstructor注解
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {
private final TestService testService;
@GetMapping("/testAsync")
public String testAsync(){
return testService.asyncMethod();
}
}
文章展示了如何在Spring中使用构造器进行bean的注入,其中被注入的类使用了final修饰。第一种方法是直接在构造器中传入依赖的TestService实例。另一种方法是利用Lombok的@RequiredArgsConstructor注解,自动为final字段生成构造器。
785

被折叠的 条评论
为什么被折叠?



