Spring AOP aspectj的使用

使用spring2.x的aop aspectj的首先需要添加asm-2.2.2.jar、asm-commons-2.2.2.jar和asm-util-2.2.2.jar,还有aspectjrt.jar和aspectjweaver.jar类包的路径之中。如果在tomcat中使用,还需要spring-tomcat-weaver.jar。

之后再配置文件中只要加入以下代码,就可以使用annotations,比较便捷的使用aop了。
<aop:aspectj-autoproxy/>


一个简单的log aop类

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AOPServiceLogger {
	public static final String ServiceEDP = "execution( * org.aaa.bbb.service.implement..*.*(..))";
	public static final String DAOEDP = "execution( * org.aaa.bbb.dao.hibernate..*.*(..))";
	private SRLogger log = SRLogger.getLogger(AOPServiceLogger.class);

	@Around(ServiceEDP)
	// spring中Around通知
	public Object logAround(ProceedingJoinPoint joinPoint) {
		log.info("Enter Service method : " + joinPoint.getSignature().getName() + " in class " +joinPoint.getTarget());
		Object[] args = joinPoint.getArgs();
		Object obj = null;
		try {
			obj = joinPoint.proceed(args);
		} catch (Throwable e) {
			log.error(e);
			e.printStackTrace();
		}
		log.info("Exit Service method : " + joinPoint.getSignature().getName() + " in class " +joinPoint.getTarget());
		return obj;
	}
	
	@Around(DAOEDP)
	// spring中Around通知
	public Object logAroundDAO(ProceedingJoinPoint joinPoint) {
		log.info("Enter DAO method : " + joinPoint.getSignature().getName() + " in class " +joinPoint.getTarget());
		Object[] args = joinPoint.getArgs();
		Object obj = null;
		try {
			obj = joinPoint.proceed(args);
		} catch (Throwable e) {
			log.error(e);
			e.printStackTrace();
		}
		log.info("Exit DAO method : " + joinPoint.getSignature().getName() + " in class " +joinPoint.getTarget());
		return obj;
	}
}

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