How do you usually use spring dependency injection?
@RestController
@RequestMapping("alarm/configs")
public class AlarmConfigController {
@Autowired
private AlarmConfigService alarmConfigService;
...
}
Is it a familiar feeling? But if you use IDEA, it will prompt you
Probably spring does not recommend using this method. There are many reasons online: https://blog.csdn.net/github_38222176/article/details/79506392
The following is the wording recommended by spring:
@RestController
@RequestMapping("alarm/configs")
public class AlarmConfigController {
private final AlarmConfigService alarmConfigService;
@Autowired
public AlarmConfigController(AlarmConfigService alarmConfigService) {
this.alarmConfigService = alarmConfigService;
}
...
}
If too many classes are injected, it looks very cumbersome. Recently, I accidentally found that using Lombok can write concise code on the Internet:
Later, I found that this method has a chance to cause Spring circular references, so it is still not recommended.
@RestController
@RequestMapping("alarm/configs")
@RequiredArgsConstructor
public class AlarmConfigController {
//这里必须是final,若不使用final,用@NotNull注解也是可以的
private final AlarmConfigService alarmConfigService;
...
}
This way of writing is actually the same as the one recommended by spring after compilation. Isn’t it very concise?
Reference https://my.oschina.net/yejunxi/blog/2209101