Spring AOP配置与应用

1. 两种方式:

a) 使用Annotation

b) 使用xml

2. Annotation

a) 加上对应的xsd文件spring-aop.xsd

b) beans.xml <aop: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) <aop:config

i.<aop:aspect …..

1. <aop:pointcut

2. <aop:before

例子:

<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>

<aop:config>

<!-- 配置一个切面 -->

<aop:aspect id="point" ref="logInterceptor">

<!-- 配置切入点,指定切入点表达式 -->

<!-- 此句也可放到 aop:aspect标签外依然有效-->

<aop:pointcut

expression=

"execution(public* com.bjsxt.service..*.*(..))"

id="myMethod"/>

<!-- 应用前置通知 -->

<aop:before method="before"pointcut-ref="myMethod" />

<!-- 应用环绕通知需指定向下进行 -->

<aop:around method="around"pointcut-ref="myMethod" />

<!-- 应用后通知 -->

<aop:after-returning method="afterReturning"

pointcut-ref="myMethod"/>

<!-- 应用抛出异常后通知 -->

<aop:after-throwing method="afterThrowing"

pointcut-ref="myMethod"/>

<!-- 应用最终通知 -->

<aop:after method="afterFinily"

pointcut="execution(public* om.bjsxt.service..*.*(..))" />

</aop:aspect>

</aop:config>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值