ApplicationContextAware接口的使用

如果一个对象希望可以取得这个对象运行所在的容器信息(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值