Analyze failures @Autowired injection

Foreword

In a recent test easyExcel tools, requires a custom class Listener for performing data read from the table to excel storage operation is performed (persistence framework for Mybatis-Plus). In the course of running, we found @Autowiredannotations Mapper object injection null, resulting in a recording operation is performed Times inserted null pointer exception, the specific code is as follows:

/**
 * @Author: WuKun
 * @Date: 2019/5/24 17:27
 */
@Component
public class ProductCmsExcelVOListener extends ExcelListener<ProductCmsExcelVO> {

    @Autowired
    private ProductMapper productMapper;
    
    @Override
    @Transactional
    public void doSomething(ProductCmsExcelVO object, AnalysisContext context) {
       //入库操作...
    }
}

identify the problem

  • First, make sure that the Listener class has been added @Componentnotes √

  • Listener class has been @ComponentScanunder annotation specified scan path (ps. Spring Boot default is to scan down from the startup class location)

  • Mapper interface is in @MapperScan√ notes under specified scanning path

  • × Listener object can not create a new way of manually

Because when I had ProductCmsExcelVOListener creating objects by ProductCmsExcelVOListener.class bytecode object newInstance()to create an object method, the essence of a new direct equivalent to the object, resulting in ProductCmsExcelVOListener the Bean is not managed by Spring, and this is where the problem lies.

Solutions

  • When you create an object ProductCmsExcelVOListener the same by @Autowiredway of injection, rather than trying to manually new.
  • Course also be used to compare the original method of obtaining Bean, as the ApplicationContext getBean(beanName);FIG.

to sum up

@AutowiredInjection failure target mainly the following two cases:

  • The first mentioned above, the caller by itself can not directly create new ways for example by A, B is a @Autowiredmember of the injection property, when A new object is created manually by way of injection B fail.
  • Another case such as the above second point positioning problem of the, Bean Spring Boot default policy is scanned from the scan start position Application class is down, when there are a plurality of program modules Spring Boot, need to ensure that other modules are added @Componentannotations the class is in the range of Spring Boot scan path, we need to use when necessary, @ComponentScan("com.xx.xx")annotations ways to expand the scanning range Bean, rather than using Spring Boot default scanning policy.

Reference links:

Guess you like

Origin blog.csdn.net/weixin_34415923/article/details/91011107