大家平时使用spring依赖注入,都是怎么写的?
@RestController
@RequestMapping("alarm/configs")
public class AlarmConfigController {
@Autowired
private AlarmConfigService alarmConfigService;
...
}
是不是很熟悉的感觉?但是呢 如果你用IDEA的话呢,它会提示你
大概就是spring 不推荐建使用这个方式。原因网上很多啦:https://blog.youkuaiyun.com/github_38222176/article/details/79506392
下面就是spring推荐的写法:
@RestController
@RequestMapping("alarm/configs")
public class AlarmConfigController {
private final AlarmConfigService alarmConfigService;
@Autowired
public AlarmConfigController(AlarmConfigService alarmConfigService) {
this.alarmConfigService = alarmConfigService;
}
...
}
若是注入的类太多的话呢,看起来挺繁琐的。最近偶然在网上发现使用Lombok可以写出简洁的代码:
后发现该方法有几率导致Spring循环引用问题,所以还是不推荐使用
@RestController
@RequestMapping("alarm/configs")
@RequiredArgsConstructor
public class AlarmConfigController {
//这里必须是final,若不使用final,用@NotNull注解也是可以的
private final AlarmConfigService alarmConfigService;
...
}
这样写实际上编译后和spring推荐的写法是一样的哦,是不是很简洁
参考https://my.oschina.net/yejunxi/blog/2209101