Spring静态注入Bean

Spring依赖注入是基于对象的,static 是基于类级别的。所以静态注入在使用的时候会抛出java.lang.NullPointerException空指针运行时异常

使用@PostConstruct方式:

1.对工具类使用@Component 注解

2.@Autowired 注解注入bean

3.@PostConstruct 使用该注解定义init()方法,在方法中给当前对象赋值

@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法

@Component
public class EasyPoiUtils {

    @Autowired
    IExportLogService exportLogService;

    private static EasyPoiUtils EasyPoiUtils;

    @PostConstruct
    public void init() {
        EasyPoiUtils = this;
    }


    /**
     * 功能描述:复杂导出Excel,包括文件名以及表名。创建表头
     *
     * @param list 导出的实体类
     * @param title 表头名称
     * @param sheetName sheet表名
     * @param pojoClass 映射的实体类
     * @param isCreateHeader 是否创建表头
     * @param fileName
     * @param response
     * @return
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }


    /**
     * 功能描述:复杂导出Excel,包括文件名以及表名,不创建表头
     *
     * @param list 导出的实体类
     * @param title 表头名称
     * @param sheetName sheet表名
     * @param pojoClass 映射的实体类
     * @param fileName
     * @param response
     * @return
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response,Integer userMasterId) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
        //导出日志
        ExportLogVO exportLogVO = new ExportLogVO();
        exportLogVO.setUserMasterId(userMasterId);
        exportLogVO.setCreateTime(new Date());
        exportLogVO.setExportTypeName(title);
        exportLogVO.setFileName(fileName);
        EasyPoiUtils.exportLogService.insert(exportLogVO);
    }
}
发布了288 篇原创文章 · 获赞 88 · 访问量 43万+

猜你喜欢

转载自blog.csdn.net/ypp91zr/article/details/89845657