静态工具类中使用注解注入service

原创
2017/04/21 16:03
阅读数 1.9K

一般需要在一个工具类中使用@Autowired 注解注入一个service。但是由于工具类方法一般都写成static,所以直接注入就存在问题。 使用如下方式可以解决:

public class TwoDeviceExcelUtil {
    public static final Logger LOGGER = LoggerFactory.getLogger(TwoDeviceExcelUtil.class);

    private static final String SHEET_TWO_DEVICE = "二次设备";

    @Autowired
    private DTUServiceImpl dtuService;
    private static TwoDeviceExcelUtil twoDeviceExcelUtil;

    public void setUserInfo(DTUServiceImpl DTUServiceImpl) {
        this.dtuService = DTUServiceImpl;
    }

    @PostConstruct
    public void init() {
        twoDeviceExcelUtil = this;
        twoDeviceExcelUtil.dtuService = this.dtuService;

    }
 //使用方法
 private static void parseTwoDevice(Sheet sheet) throws Exception {
      
        //此处省略代码
    String model = dtu.get("dtuModel");
    //使用方式
    Integer channelCount = twoDeviceExcelUtil.dtuService.channelCount(model);

        
    }
}```
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部