ApplicationContextAware接口的使用
程序员文章站
2022-05-25 16:12:58
...
如果一个对象希望可以取得这个对象运行所在的容器信息(ApplicationContext)的话,这个对象
不妨实现这个接口(ApplicationContextAware)。
继承这个接口,可以获取应用启动时,spring 容器已经实例化的bean,而不用自己再去实例化重复的类,浪费资源。
项目开发系统应用的日志记录到数据库中去,于是就想用线程池方式,提交任务到线程池,然后并发的统一的记录日志。
所以需要把DaXtLogService 初始化到Runnable中去。
package com.dangan.bean;
import javax.annotation.Resource;
import javax.swing.Spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextAware;
import com.dangan.dao.impl.DaXtLogDaoImpl;
import com.dangan.dao.pojo.DaXtLog;
import com.dangan.service.DaXtLogService;
import com.dangan.service.impl.DaXtLogServiceImpl;
import com.dangan.utils.SpringContextUtils;
public class LogRunnable implements Runnable {
private DaXtLog daXtLog;
private DaXtLogService daXtLogService;
public LogRunnable(String type, String description, int humanId,
String humanName, String ip, String flh) {
daXtLog=new DaXtLog(humanId, humanName, ip, type, description, flh);
daXtLogService=(DaXtLogService) SpringContextUtils.getObject("daXtLogService");
}
@Override
public void run() {
if(daXtLog!=null){
try {
daXtLogService.save(daXtLog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.dangan.utils;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import com.dangan.dao.pojo.DaXtLog;
public class LogService {
private final BlockingQueue<DaXtLog> logsQueue=new LinkedBlockingQueue<DaXtLog>();
private ExecutorService executorService=Executors.newScheduledThreadPool(3);
private static final LogService logService=new LogService();
public static LogService getInstance(){
return logService;
}
public void log(Runnable logRunnable){
executorService.submit(logRunnable);
}
}
package com.dangan.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtils implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
this.applicationContext=arg0;
}
public static Object getObject(String beanId){
return applicationContext.getBean(beanId);
}
}
转载于:https://my.oschina.net/u/255939/blog/538053