今天在一个普通类中注入service时出现了一个问题,我用@Autowired注入的service为null。最终我是通过以下方案解决的。

1.在类上标注该类为组件也就是@Component

2.静态初始化当前类

3.在初始化service的方法上加上注解@PostConstruct,这样方法就会在Bean初始化之后被Spring容器执行

4.调用时通过类来调用

@Component
public class LogUtil {
@Autowired
private LogService logService;
private static LogUtil logUtil; // 静态初使化当前类

public static void saveLog(String userName, String result) {
Log log = new Log(userName+"", result);
try {

logUtil.logService.add(log);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@PostConstruct
public void init() {
logUtil = this;
logUtil.logService = this.logService;

}
}