Zsnd / blog

0 stars 0 forks source link

Spring ioc 注入规范化与优化 #5

Open Zsnd opened 6 years ago

Zsnd commented 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
}

构造函数注入的优点:

kid1412621 commented 5 years ago

https://www.baeldung.com/spring-injection-lombok

kid1412621 commented 5 years ago

想我问下 lombok 生成的构造方法是怎么加上 @Autowired 注解的? 还是说是不用加? 懂了, If a bean has one constructor, you can omit the @Autowired .

kid1412621 commented 5 years ago

还有, 需要使用 @Qualifier 的时候这种方式适用吗?

kid1412621 commented 5 years ago

还有就是相互依赖的时候

Zsnd commented 5 years ago

不行,上述方式本质上只是针对构造函数注入的一种简化形式,不能替代属性注入。