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

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

在applicationContext.xml 配置文件中加入类似如下配置信息 Xml代码
<bean id="commonAdvise"></bean> 
<bean id="commonProxy"> 
    <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> 
 
两个类的源码如下 Java代码
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("===========================");  
      
    }  
 

Java代码
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中的代码,打印信息如下:

Java代码
===========================  
目标方法返回值:[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 
目标方法参数列表:  
=========================== 

 这种方式绝对是代码零侵入性,推荐大家使用。

  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓