兩種方法配置
http://www.cnblogs.com/davidwang456/p/4013631.html
1.注解
1)Aspect定義一個切面 在切面定義切入點@Pointcut
并定義通知類型@Before @AfterReturning @After @AfterThrowing @Around
2)開發(fā)需要被攔截的類
3)將切面配置到xml中初狰,也可以使用自動掃描Bean的方式缓熟,交由SpringAop容器管理
需要引用的jar包aspectjweaver.jar aspectjrt.jar
@Component
//聲明這是一個切面Bean
@Aspect
public class ServiceAspect {
private final static Log log = LogFactory.getLog(ServiceAspect.class);
//配置切入點,該方法無方法體,主要為方便同類中其他方法使用此處配置的切入點
@Pointcut("execution(* cn.ysh.studio.spring.aop.service..*(..))")
public void aspect(){ }
/*
* 配置前置通知,使用在方法aspect()上注冊的切入點
* 同時接受JoinPoint切入點對象,可以沒有該參數(shù)
*/
@Before("aspect()")
public void before(JoinPoint joinPoint){
if(log.isInfoEnabled()){
log.info("before " + joinPoint);
}
}
//配置后置通知,使用在方法aspect()上注冊的切入點
@After("aspect()")
public void after(JoinPoint joinPoint){
if(log.isInfoEnabled()){
log.info("after " + joinPoint);
}
}
//配置環(huán)繞通知,使用在方法aspect()上注冊的切入點
@Around("aspect()")
public void around(JoinPoint joinPoint){
long start = System.currentTimeMillis();
try {
((ProceedingJoinPoint) joinPoint).proceed();
long end = System.currentTimeMillis();
if(log.isInfoEnabled()){
log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms!");
}
} catch (Throwable e) {
long end = System.currentTimeMillis();
if(log.isInfoEnabled()){
log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());
}
}
}
//配置后置返回通知,使用在方法aspect()上注冊的切入點
@AfterReturning("aspect()")
public void afterReturn(JoinPoint joinPoint){
if(log.isInfoEnabled()){
log.info("afterReturn " + joinPoint);
}
}
//配置拋出異常后通知,使用在方法aspect()上注冊的切入點
@AfterThrowing(pointcut="aspect()", throwing="ex")
public void afterThrow(JoinPoint joinPoint, Exception ex){
if(log.isInfoEnabled()){
log.info("afterThrow " + joinPoint + "\t" + ex.getMessage());
}
}
}
2.xml方式