`

使用AOP实现监控日志并保存

阅读更多
最近项目中要做个效能监控的功能,经过考虑,觉得选择spring的AOP来实现。必须放在Web端。

例子如下:
import java.util.Date;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;

import com.csair.amp.web.webinf.common.model.LoginInfo;
import com.csair.smms.effmonitor.dto.MonitorLog;
import com.csair.smms.effmonitor.service.MonitorService;
import com.opensymphony.xwork2.ActionContext;

/**
 * 效能监控日志类
 * 
 * @author ahomeeye
 * 
 *         2012-7-11 下午2:32:34
 */
@Aspect
public class EfficiencyMonitor {

	@Autowired
	private MonitorService monitorService;//保存日志信息的业务实现

	// 登录日志,代表监控com.csair.amp.web.webinf.common.LoginAction类的login方法,可用通配符*
	@After("execution(* com.csair.amp.web.webinf.common.LoginAction.login())")
	public void loginLog() {
        //从session中获取用户信息
		LoginInfo u = (LoginInfo) ActionContext.getContext().getSession()
				.get("user");
		MonitorLog m = new MonitorLog();
		m.setUsername(u.getUsername());
		m.setLogtime(new Date());
		m.setFunction(MonitorConstants.LOGIN);
		m.setClassName("com.csair.amp.web.webinf.common.LoginAction");
		m.setMethodName("login");
		monitorService.insertMonitorLog(m);//保存日志信息

		System.out.println("-------用户登录--username=" + u.getUsername());
	}
}


需要导入两个AspectJ库:aspectjweaver.jar和aspectj.jar。

JavaBean类
public class MonitorLog implements Serializable {
	private static final long serialVersionUID = 7707875472196483005L;
	private int id;// 编号
	private String username;// 用户名
	private Date logtime;// 使用时间
	private String function;// 使用功能
	private String className;// 类名
	private String methodName;// 方法名
        //省略setter和getter方法
}


在applicationContext.xml文件里加入如下代码:
<!-- 指定自动搜索Bean组件、自动搜索切面类,前一个代表搜索Bean的包,后一个代表搜索切面类的包-->
   <context:component-scan base-package="com.csair.amp.web.webinf,com.csair.amp.web.webinf.effmonitor">
	<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
   </context:component-scan>
	<!-- 启动@AspectJ支持 -->
	<!--<aop:aspectj-autoproxy/> 此标记与下面一行等效-->
	<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>


如果项目中使用了spring的自动装配(@Autowired)功能,还行在struts.xml文件中加入下面一行,意思是始终使用自动装配功能:
<constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true" />
  • lib.zip (1.6 MB)
  • 下载次数: 62
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics