spring 在单例类中使用注解注入bean

本文转自 http://www.cnblogs.com/xiaxinggege/p/5893160.html
重点是@PostConstruct

/**
* @author: jerry
* @Email:
* @Company:
* @Action: 日志处理工具类
* @DATE: 2016-9-19
*/

@Component//泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注
public class LogUtil {

@Autowired<br>//注意这里非静态
private AdminLogService logService;

private static LogUtil logUtil;

@PostConstruct //@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
public void init() {
logUtil = this;
logUtil.logService = this.logService;
}
public AdminLogService getUserService() {
return logService;
}
public void setUserService(AdminLogService userService) {
this.logService = userService;
}
public static void addLog(LoginInfo loginInfo,String desc){
//添加日志
AdminLog log=new AdminLog();
log.setCreatetime(new Date());
log.setDescription(desc);
try {
log.setCuid(loginInfo.getUser().getId());
log.setCreateuser(loginInfo.getUser().getAccount());
logUtil.logService.insertLog(log);
} catch (Exception e) {
log.setCuid(0);
log.setCreateuser("unknow");<br>//调用时通过类去调
logUtil.logService.insertLog(log);
}

}
}

猜你喜欢

转载自blog.csdn.net/Aseasonv/article/details/79024771