spring的AOP调用(四)前后通知完整实现代码

spring的AOP调用(四)前后通知完整实现代码

测试前、后通知的AOP调用,其实和环绕相比,修改的配置和代码很少。
主要配置文件如下:
<aop:config>
<aop:aspect ref="managerAOP">
   <aop:pointcut id="theExecutionOfBizOrderSaveMethod"
    expression="execution(*
com.sillycat..*.dao.*DAO.save*(..)) and args(obj)" />
   <aop:before pointcut-ref="theExecutionOfBizOrderSaveMethod"
    method="save" />
</aop:aspect>
</aop:config>
<aop:config>
<aop:aspect ref="managerAOP">
   <aop:pointcut id="theExecutionOfBizOrderDeleteMethod"
expression="execution(* com.sillycat..*.dao.*DAO.delete*(..)) and args(obj)" />
   <aop:after-returning pointcut-ref="theExecutionOfBizOrderDeleteMethod"
    method="delete" />
</aop:aspect>
</aop:config>
配置文件修改了before前置通知,after-returning后置通知。

类ManagerAOPImpl.java中就不再需要调用proceed方法去invoke原来的方法了,因为不论是before还是after-returning,原方法都已经被调用了,类ManagerAOPImpl.java如下:
package com.sillycat.easyaop.service.aop;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Service;
import com.sillycat.easyaop.dao.RoleDAO;
import com.sillycat.easyaop.model.Role;
@Service("managerAOP")
public class ManagerAOPImpl {
private static Log log = LogFactory.getLog(ManagerAOPImpl.class);
private static final String BASE_MANAGER_SAVE = "com.sillycat.easyaop.dao.impl.RoleDAOImpl";
private RoleDAO roleDAO;
@Resource(name = "roleDAO")
public void setRoleDAO(RoleDAO roleDAO) {
   this.roleDAO = roleDAO;
}
public void delete(JoinPoint call, Object obj) {
   log.debug("target name is : " + call.getTarget());
   log.debug("args is : " + obj);
   if (checkIfNeedProccess(call, obj)) {
    log.debug("object is extends User,begin to ivoke roleDAO!");
    roleDAO.delete((Role) obj);
   }
}
public void save(JoinPoint call, Object obj) {
   log.debug("target name is : " + call.getTarget());
   log.debug("args is : " + obj);
   if (checkIfNeedProccess(call, obj)) {
    log.debug("object is extends User,begin to ivoke roleDAO!");
    roleDAO.save((Role) obj);
   }
}
private boolean checkIfNeedProccess(JoinPoint call, Object obj) {
   boolean flag = false;
   if (!BASE_MANAGER_SAVE.equalsIgnoreCase(getCompleteTargetName(call
     .getTarget()))
     && (obj instanceof Role)) {
    flag = true;
   }
   return flag;
}
private String getCompleteTargetName(Object target) {
   String className = "";
   if (target != null) {
    className = target.toString();
    int loc = className.indexOf("@");
    if (loc >= 0) {
     className = className.substring(0, loc);
    }
   }
   return className;
}
}

发现情况和环绕通知一样。解决不了在公司项目容器中调用三次的问题。再次查看异同,也没有比较出来,查看以前写的AOP处理memcache,ehcache,oscache的项目,决定采用RegexpMethodPointcutAdvisor再试试。

你可能感兴趣的:(DAO,apache,spring,AOP)