Open Zsnd opened 6 years ago
public class DataReportingServiceImpl implements DataReportingService { @Autowired private DivisionReportMapper divisionReportMapper; @Autowired private DivisionReportProgressMapper divisionReportProgressMapper; @Autowired private ReportMapper reportMapper; @Autowired private ReportProgressMapper reportProgressMapper; @Autowired private DivisionService divisionService; @Autowired private CurrentMonthService currentMonthService; //some code }
可简化为:
import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class DataReportingServiceImpl implements DataReportingService { private final @NonNull DivisionReportMapper divisionReportMapper; private final @NonNull DivisionReportProgressMapper divisionReportProgressMapper; private final @NonNull ReportMapper reportMapper; private final @NonNull ReportProgressMapper reportProgressMapper; private final @NonNull DivisionService divisionService; private final @NonNull CurrentMonthService currentMonthService; //some code }
构造函数注入的优点:
lombok
http://olivergierke.de/2013/11/why-field-injection-is-evil/ https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-autowired-annotation
https://www.baeldung.com/spring-injection-lombok
想我问下 lombok 生成的构造方法是怎么加上 @Autowired 注解的? 还是说是不用加? 懂了, If a bean has one constructor, you can omit the @Autowired .
还有, 需要使用 @Qualifier 的时候这种方式适用吗?
还有就是相互依赖的时候
不行,上述方式本质上只是针对构造函数注入的一种简化形式,不能替代属性注入。
可简化为:
构造函数注入的优点:
lombok
显著减少模板代码