yuyee

使用Annotation来完成spring aop

spring AOP中,可以通过annotation来简化XML上的配置,可以很灵活的使切面切入到自己想要的方法上,而不需要象aop:config里一定要切入到特定命名方法上
使用annotation来表示pointcut,需要在xml里配置org.springframework.aop.support.annotation.AnnotationMatchingPointcut,
如:<bean name="timeoutPointcut"
class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut">
<constructor-arg index="0"
value="com.hengtian.fxfundsystem.aop.annotation.UseAOPAnnotation">
</constructor-arg>
<constructor-arg index="1"
value="com.hengtian.fxfundsystem.aop.annotation.TimeoutAnnotation" />
</bean>
第一个参数是标在目标类上的annotation,第二天参数是标注在方法上的Annotation
因此,首先要在自己的工程里定义2个annotation,一个为TimeoutAnnotation,一个为UseAOPAnnotation
@Target({ElementType.TYPE })//表示类标注
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface UseAOPAnnotation {

}
@Target({ElementType.METHOD})//表示方法标注
@Retention(RetentionPolicy.RUNTIME)
public @interface TimeoutAnnotation {
/**
* 默认值(-1):表示不启用超时
*/
public static final long DefaultValue = -1;

/**
* 超时时间,单位是ms
* @return
*/
long value() default DefaultValue;

}
在需要AOP的类上使用
@UseAOPAnnotation
@Component("StrongDuck")  
public class StrongDuck {
@TimeoutAnnotation(70000)
public void say(){
System.out.println("I am a strong duck");
}
}
timeout通知:
public class TimeoutAdvice implements MethodInterceptor {

/*
* (non-Javadoc)
* @see
* org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept
* .MethodInvocation)
*/
public Object invoke(final MethodInvocation methodInvocation)
throws Throwable {

Method targetMethod = methodInvocation.getMethod();
TimeoutAnnotation timeoutAnnotation = targetMethod
.getAnnotation(TimeoutAnnotation.class);
if (timeoutAnnotation != null) {
long waitTime = timeoutAnnotation.value();
if (waitTime != TimeoutAnnotation.DefaultValue) {
Future<?> task = ThreadManager.ExecutorService
.submit(encapsulateSyncToAsync(methodInvocation));
return getAsyncResult(waitTime, task);
}

}
return methodInvocation.proceed();
}
XML中配置拦截器:
<bean id="timeoutInterceptor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="timeoutAdvice" />
<property name="pointcut" ref="timeoutPointcut" />
</bean>
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
<property name="proxyTargetClass"><!-- 基于类的代理 -->
<value>true</value>
</property>
</bean>
这样,spring就会为你生成aop代理类实现AOP


posted on 2010-10-25 16:52 羔羊 阅读(1797) 评论(0)  编辑  收藏 所属分类: aop