静态方法如何使用@Autowired注入
可以编写一个工具类,如下:其中的getAllTargetInfo()方法,便可以在静态类中,使用对象调用。
package com.hontye.parameter.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.hontye.parameter.entity.TargetInfo;
import com.hontye.parameter.service.TargetInfoService;
import org.springframework.stereotype.Component;
import java.util.List;
import javax.annotation.PostConstruct;
@Component
public class AutoLoginUtil {
private static Logger logger = LoggerFactory.getLogger(AutoLoginUtil.class);
@Autowired
private TargetInfoService targetInfoService;
private static AutoLoginUtil autoLoginUtil;
public void setTargetInfoService(TargetInfoService targetInfoService) {
this.targetInfoService = targetInfoService;
}
@PostConstruct
public void init() {
autoLoginUtil = this;
autoLoginUtil.targetInfoService = this.targetInfoService;
}
//此方法可供其他类静态方法调用
public List<TargetInfo> getAllTargetInfo() {
return autoLoginUtil.targetInfoService.findAll();
}
}