AOP之注解

1)接口Waiter

2)实现类WaiterImp

@Component("waiter")  //扫描对象,对象名waiter
public class WaiterImp implements Waiter{...}

3)通知类

@Aspect      ///面切(拦截哪个方法)
@Component   //扫描对象
public class NotUsfulAspect {
@Pointcut("execution(* greetTo(..))")   //统一面切(统一拦截方法) || 如果是所有方法"execution(* package.*.*(..))"
private void anyMethod(){}

@Before("anyMethod()")
public void before(){
System.out.println("前置通知");
}
@After("anyMethod()&&args(name)")
public void after(String name){
System.out.println("最终通知"+name);
}

@AfterReturning(pointcut="anyMethod()",returning="result")
public void afterReturn(String result){
System.out.println("后置通知"+result);
}

@AfterThrowing(pointcut="anyMethod()",throwing="e")
public void afterThrow(Exception e){
System.out.println("例外通知:"+e);
}

@Around("anyMethod()") //环绕通知--->前后通知
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("start...");
Object result = pjp.proceed();
System.out.println("end...");
return result;
}


}

4)测试类

public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("aop/bean1.xml");
Waiter waiter = applicationContext.getBean("waiter",Waiter.class);   //waiter是WaiterImp对象

waiter.greetTo("Mis niu");
waiter.serverTo("Mis cui");
}

posted @ 2016-06-17 11:00  乱世_独自美  阅读(62)  评论(0)    收藏  举报