Spring AOP配置与应用

2014-11-24 09:07:05 · 作者: · 浏览: 1
1. 两种方式:
a) 使用Annotation
b) 使用xml
2. Annotation
a) 加上对应的xsd文件spring-aop.xsd
b) beans.xml aspectj-autoproxy />
c) 此时就可以解析对应的Annotation了
d) 建立我们的拦截类
e) 用@Aspect注解这个类
f) 建立处理方法
g) 用@Before来注解方法
h) 写明白切入点(execution …….)
i) 让spring对我们的拦截器类进行管理@Component
3. 常见的Annotation:
a) @Pointcut 切入点声明以供其他方法使用 , 例子如下:
@Aspect
@Component
publicclass LogInterceptor {
@Pointcut("execution(public * com.bjsxt.dao..*.*(..))")
publicvoid myMethod(){}
@Around("myMethod()")
publicvoidbefore(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("method before");
pjp.proceed();
}
@AfterReturning("myMethod()")
publicvoid afterReturning() throws Throwable{
System.out.println("method afterReturning");
}
@After("myMethod()")
publicvoid afterFinily() throws Throwable{
System.out.println("method end");
}
}
b) @Before 发放执行之前织入
c) @AfterReturning 方法正常执行完返回之后织入(无异常)
d) @AfterThrowing 方法抛出异常后织入
e) @After 类似异常的finally
f) @Around 环绕类似filter , 如需继续往下执行则需要像filter中执行FilterChain.doFilter(..)对象一样 执行 ProceedingJoinPoint.proceed()方可,例子如下:
@Around("execution(* com.bjsxt.dao..*.*(..))")
publicvoidbefore(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("method start");
pjp.proceed();//类似FilterChain.doFilter(..)告诉jvm继续向下执行
}
4. 织入点语法
a) void !void
b) 参考文档(* ..)
如果execution(* com.bjsxt.dao..*.*(..))中声明的方法不是接口实现则无法使用AOP实现动态代理,此时可引入包” cglib-nodep-2.1_3.jar” 后有spring自动将普通类在jvm中编译为接口实现类,从而打到可正常使用AOP的目的.
5. xml配置AOP
a) 把interceptor对象初始化
b)
i.
1.
2.
例子:
expression=
"execution(public* com.bjsxt.service..*.*(..))"
id="myMethod"/>
pointcut-ref="myMethod"/>
pointcut-ref="myMethod"/>
pointcut="execution(public* om.bjsxt.service..*.*(..))" />