Web开发通用监控类解决方案(代码零侵入性)

[/code]我们开发网站的过程中,经常会碰到这种情况,当调用某个类中函数的时候,需要记录一些东西或触发某些事件,如何来实现呢?如当缓存中的对象不是最新时,需及时更新缓存对象,当调用某些类的某些方法时,需要记录某些日志信息等,这种应用无处不在,我们如何实现他,利用Spring框架的AOP为例,记录一下他的实现方法

在applicationContext.xml 配置文件中加入类似如下配置信息
[code="xml"]<bean id="commonAdvise" class="cn.hj.advise.CommonAdvise"></bean>
<bean id="commonProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref bean="groupService" />
</property>
<property name="proxyInterfaces">
<value>cn.hj.service.IGroupService</value>
</property>
<property name="interceptorNames">
<list>
<value>commonAdvise</value>
</list>
</property>
</bean>


两个类的源码如下
public class CommonAdvise implements AfterReturningAdvice{   
private GroupService groupService;
public GroupService getGroupService() {
return groupService;
}
public void setGroupService(GroupService groupService) {
this.groupService = groupService;
}
public void afterReturning(Object returnValue, Method method, Object[] target_arg,
Object target) throws Throwable {
System.out.println("===========================");
System.out.println("目标方法返回值:"+returnValue+",目标方法:"+method+",目标对象:"+target+"目标方法参数列表:\n");
if(target_arg!=null){
for(int i=0;i<target_arg.length;i++){
System.out.println("Object["+i+"]:"+target_arg[i]);
}
}
System.out.println("===========================");

}

}

public interface IGroupService {   
public void addGroup(Group group);
public void delGroup(Group group);
public void modGroup(Group group);
public Group findGroup(String groupid);
public List listGroup();
}


测试代码
在我程序的任何地方调用IGroupService的listGroup时,都会自动执行commonAdvise中的代码,打印信息如下:
===========================   
目标方法返回值:[cn.hj.model.Group@1bb205a, cn.hj.model.Group@48fbc0, cn.hj.model.Group@18837f1]
目标方法:public abstract java.util.List cn.hj.service.IGroupService.listGroup()
目标对象:cn.hj.service.GroupService@10f0a0
目标方法参数列表:
===========================


这种方式绝对是代码零侵入性,推荐大家使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值