嗨,朋友,今天在Spring项目中接触到一种新的对象注入方式,利用的是我们常用的一个工具:lombok
。
回顾一下我曾经在Spring项目中经常使用的对象注入方式:
第一种:
注解:@Autowired
,它是在IOC容器中根据对象类型来寻找对象实例,它是Spring框架提供的。
第二种:
注解:@Resource
,它是首先根据对象别名(@Service("别名"))寻找对象实例,其次根据对象类型来寻找对象实例,它是JDK自身提供的。
第三种:
今天刚学到的:lombok工具
+ 注解:@RequiredArgsConstructor
【这个注解标记在类上,实现多个对象实例的引入】,但是,需要在你引入的对象上,使用 final
来声明。测试代码如下:
@RestController
@RequiredArgsConstructor
public class DemoController {
// @Autowired
// private DemoService demoService;
// @Resource
// private DemoService demoService;
private final DemoService demoService;
@GetMapping("/demo/{name}")
public String sayHello(@PathVariable("name") String name) {
String res = demoService.sayHello(name);
return res;
}
}
实际的底层实现是这个样子的:
private DemoService demoService;
public DemoController(DemoService demoService) {
this.demoService = demoService;
}
在Spring容器对象注入(DI)的方式三种:1:set方法注入,2:构造方法注入,3:我记得是在配置文件(xml)利用的也是set方式注入的来(我用的不多,几乎没有)。
我目前喜欢使用的:@Resource
,再见。