第一次写,稍有不慎,见谅,话不多说 进入正题
之前的编码都是一贯使用@Autowired.用到什么注入什么,@autowired满天飞
在此介绍一个可以简化代码的插件lombok (官方API) -->https://projectlombok.org/features/all
public class TestController{
private final TestService testService;
public void test() {
testService.test()
}
}
再看TestService
@RequiredArgsConstructor
public class TestService {
private final TestMapper testMapper
public void test(){
........
}
}
@RequiredArgsConstructor是lombok的一个注解,它主要用来做什么的呢?
官方给出的解释是:
Generates constructor that takes one argument per final / non-null field.
所以它会为final和nonnull的属性作为参数产生一个构造函数。
spring的官方解释中:
Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
Regarding the default constructor: You either need the default constructor, a constructor with the Autowired annotation when you have multiple constructors, or only one constructor in your class with or without the Autowired annotation.
**结论就是:
If a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
如果一个类(配置为Spring bean)只有一个构造函数,那么可以省略自动生成的注释,Spring将使用这个构造函数并注入所有必要的依赖项。
以上仅是一种编码风格,并不是@Autowired会被替代