基于 Aspect 使用注解
1. spring 不会自动去寻找注解,必须告诉 spring 哪些包下的类中可能有注解
引入 xmlns:context
< context: component-scan base-package = " com.youdian.advice" >
</ context: component-scan>
2. @Component
相当于 如果没有参数,把类名首字母变小写,相当于<beanid=””/> @Component(“自定义名称”)
3. 实现步骤
在 spring 配置文件中设置注解在哪些包中
< context: component-scan base-package = " com.youdian.advice,com.youdian.test" >
</ cont ext: component-scan>
在 Demo 类中添加@Componet 在方法上添加@Pointcut(“”) 定义切点
@Component
public class Demo {
@Pointcut ( "execution(* com.youdian.test.Demo.demo1())" )
public void demo1 ( ) throws Exception{
System. out. println ( "demo1" ) ;
}
}
在通知类中配置 ① @Component 类被 spring 管理 ② @Aspect 相当于aop:aspect/ 标签 表示通知方法在当前类中
@Component
@Aspect
public class MyAdvice {
@Before ( "com.youdian.test.Demo.demo1()" )
public void mybefore ( ) {
System. out. println ( "前置" ) ;
}
@After ( "com.youdian.test.Demo.demo1()" )
public void myafter ( ) {
System. out. println ( "后置通知" ) ;
}
@AfterThrowing ( "com.youdian.test.Demo.demo1()" )
public void mythrow ( ) {
System. out. println ( "异常通知" ) ;
}
@Around ( "com.youdian.test.Demo.demo1()" )
public Object myarround ( ProceedingJoinPoint p) throws Throwable{
System. out. println ( "环绕-前置" ) ;
Object result = p. proceed ( ) ;
System. out. println ( "环绕-后置" ) ;
return result;
}
}