近日由于要对业务逻辑层的返回值进行一下处理,所以看看了spring 2.0中关于AOP开发部分的内容,在这里做个笔记,以免过几天又给忘了
。如果能对您有帮助,就帮忙顶一下。
一、AOP的基本概念
- Aspect(切面),一个横切多个对象的关注点的模块;
- Joint point(连接点),程序执行中的一个点,比如执行一个方法或者是处理一个异常;
- Advice(建议??),一个aspect在一个特殊的Join point的行为或动作。包括:before, after returning, after throwing, after(finally), around五种;
- Pointcut(切入点),匹配连接点一个断言。advice与Pointcut表达式相关联,并且在任何join point与pointcut相匹配时执行。
二、AOP with spring
spring 2.0引入了一个简单并且功能更加强大的方法来自定义aspect。自定义aspect时有两种风格:schema-based和@aspectJ。
- @aspectJ风格指在一个正常的java类上添加java 5的注解来声明一个aspect,它是由AspectJ项目提出的,详细信息请查看http://www.eclipse.org/aspectj,这里不讨论这种方式。
- shcema-based风格是指在spring bean的配置文件中通过新的"aop"命名空间标记定义一个aspect。
aop命名空间定义
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
三、schema-based
定义aspect
- <aop:config>
- <aop:aspect id="myAspect" ref="aBean">
- ...
- aop:aspect>
- >
- <bean id="aBean" class="...">
- ...
- >
定义pointcut
- <aop:config>
- <aop:pointcut id="businessService"
- expression="execution(* com.xyz.myapp.service.*.*(..))"/>
- >
定义Advice
- <aop:aspect id="beforeExample" ref="aBean">
- <aop:before pointcut-ref="dataAccessOperation" method="doAccessCheck"/>
- <aop:after-returning pointcut-ref="dataAccessOperation"returning="retVal" method="doAccessCheck"/>
- <aop:after-throwing pointcut-ref="dataAccessOperation" throwing="dataAccessEx" method="doRecoveryActions"/>
- <aop:after pointcut-ref="dataAccessOperation" method="doReleaseLock"/>
- <aop:around pointcut-ref="businessService" method="doBasicProfiling"/>
- ...
- >
四、例子
配置
- <aop:config>
- <aop:pointcut id="pointcut_lazyProcess"
- expression="this(com.xucons.arch.BusinessLogic) and execution(public !void *(..))"/>
- <aop:aspect id="aspect_lazyProcess" ref="lazyProcess">
- <aop:around
- pointcut-ref="pointcut_lazyProcess"
- method="processUninitializedObject"/>
- aop:aspect>
- >
- <bean id="lazyProcess" class="com.qusiness.arch.rt.LazyProcess" />
实现
- public class LazyProcess {
- static Logger logger = Logger.getLogger(LazyProcess.class.getName());
- public Object processninitializedObject(ProceedingJoinPoint pjp) throws Throwable {
- Object retVal = pjp.proceed(); if (retVal != null) {
- logger.info(">>processing uninitialized business object...");
- if (retVal instanceof Date ) {
- retVal = new Date(((Date) retVal).getTime());
- } else {
- process(retVal);
- }
- }
- return retVal;
- }
- }
本文介绍了Spring 2.0中AOP的概念与应用,包括Aspect、Jointpoint、Advice和Pointcut等基本要素,并通过示例展示了如何使用schema-based风格定义Aspect、Pointcut及Advice。
1285

被折叠的 条评论
为什么被折叠?



