package aop;
import java.util.Arrays;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* 使用Schema实现切面编程
* @author 尹涛
*
*/
public class UserSerciceLogger {
private static final Logger log=Logger.getLogger(ErroorLogger.class);
/**
* 前置增强
* @param jp
*/
public void before(JoinPoint jp){
log.info("前置增强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs()));
}
/**
* 后置增强
* @param jp
* @param retutnValue
*/
public void afterReturning(JoinPoint jp,Object retutnValue){
log.info("后置增强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs())+",返回值是"+retutnValue);
}
/**
* 异常增强
* @param jp
* @param e
*/
public void afterThrowing(JoinPoint jp,NullPointerException e){
log.info("异常处理增强,"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,发生异常"+e);
}
/**
* 环绕增强
* @param jp
* @return
*/
public Object around(ProceedingJoinPoint jp){
Object result=null;
log.info("环绕强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs()));
try {
result=jp.proceed();
log.info("环绕增强方法,调用了"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法,参数是"+Arrays.toString(jp.getArgs())+",返回值是"+result);
} catch (Throwable e) {
log.info(jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法异常"+e);
}
return result;
}
/**
* 最终增强
* @param jp
*/
public void after(JoinPoint jp){
log.info("最终增强"+jp.getTarget().getClass().getSimpleName()+"的"+jp.getSignature().getName()+"方法执行结束");
}
}
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<bean id="userDao" class="dao.impl.UserDaoImpl"></bean>
<bean id="userSercice" class="sercice.impl.UserSerciceImpl" p:ud-ref="userDao"></bean>
<!-- 声明所在方法的Bean -->
<bean id="userLogger" class="aop.UserSerciceLogger"></bean>
<!-- 定义切入点 -->
<aop:config>
<aop:pointcut expression="execution(* sercice.impl.*.*(..))" id="pointcut"/>
<aop:aspect ref="userLogger">
<!--配置前置增强 -->
<aop:before method="before" pointcut-ref="pointcut"/>
<!-- 后置增强 returning参数与方法中参数名称对应-->
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="retutnValue"/>
<!-- 异常增强 -->
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
<!-- 环绕增强 -->
<aop:after method="after" pointcut-ref="pointcut"/>
<!-- 环绕增强 -->
<aop:around method="around" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>