在使用 SpringBoot 框架开发过程中,一些工具类、静态非Controller 类需要调用由Spring 管理的Service 层类;如果直接使用@Autowired注解引用Service类的方法,会报 null 异常。这是因为工具类创建过程中,不能使用@Autowired注解引用Service类的方法。
一、解决方法
package com.bootdo.publicOrder.utils;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import com.bootdo.publicOrder.domain.OrderInfoCom;
import com.bootdo.publicOrder.domain.OrderReturnInfoCom;
import com.bootdo.publicOrder.service.OrderInfoService;
@Configuration //将工具类声明为Spring组件;也可以使用 Component 等
public class PublicMiddleUtil {
@Autowired
private OrderInfoService orderService;
//静态初始化当前类
public static PublicMiddleUtil middleUtil;
//在方法上加 PostConstruct 注解;方法会在Bean 初始化之后被Spring 容器执行。
//Bean 初始化包括:实例化Bean、装配Bean的属性(依赖注入)
//在初始化的时候初始化静态对象和它的静态成员变量bean对象,静态存储下来,防止被释放
@PostConstruct
public void init() {
middleUtil = this;
middleUtil.orderService = this.orderService;
}
public static OrderReturnInfoCom middleEntrance(OrderInfoCom f) {
return new PublicMiddleUtil().orderEntrance(f);
}
public OrderReturnInfoCom orderEntrance(OrderInfoCom f) {
OrderReturnInfoCom result = new OrderReturnInfoCom();
if (null!=f) {
......
if("queryProductsList".equals(f.getMethod())) {
result = middleUtil.orderService.queryOrderProducts(f); //注入的属性,使用静态对象调用
}
}
return result;
}
}