@RestController
public class MyController {
@Autowired
private MyService service;
}
因此,spring中不推荐使用字段注入
,建议使用构造函数注入
@RestController
public class MyController {
private MyService service;
@Autowired
public void setService(MyService service) {
this.service = service;
}
}
@RestController
public class MyController {
private final MyService service;
public MyController(MyService service) {
this.service = service;
}
}
构造器模式优化
@RestController
@RequiredArgsConstructor
public class MyController {
private final MyService service;
}
通过lombok的注解 @RequiredArgsConstructor,让类在编译的时候自动生成对应的含参构造函数。
@RequiredArgsConstructor 注解是针对标有 @NonNull 注解的变量和 final 变量进行参数的构造方法。