Aopalliance

Aopalliance is a joint open-source project between several software engineering people who are interested in AOP and Java.

入门例子

maven 引入

  [xml]
1
2
3
4
5
<dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency>

编写 AOP 实现

为了突出重点,省略掉相关的具体实现。

详情参考 CacheInterceptor.java

  [java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.framework.framework.cache.interceptor; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; /** * @author houbinbin * @on 17/1/7 * 模仿spring的CacheInterceptor * 不过spring又进行了更多的封装。此处实现比较简单。 */ public class CacheInterceptor implements MethodInterceptor { protected final Log logger = LogFactory.getLog(this.getClass()); /** * @Cacheable & @CachePut 都应该是单独使用的。 * AnnotationUtils.findAnnotation * @param methodInvocation * @return * @throws Throwable */ @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { // 其他注解相关实现 return methodInvocation.proceed() } }

优点

这种优点是不用写一个 AOP 都要依赖于 spring-aop。

但是怎么和 spring 结合呢?

结合 Spring

  [xml]
1
2
3
4
5
6
7
8
9
10
<bean id="cacheInterceptor" class="com.framework.framework.cache.interceptor.CacheInterceptor"> <property name="cacheManager" ref="cacheManager" /> </bean> <aop:config> <aop:pointcut id="cachePointcut" expression="@annotation(com.framework.framework.cache.annotation.CacheGetSet) or @annotation(com.framework.framework.cache.annotation.CacheRemove)" /> <aop:advisor advice-ref="cacheInterceptor" pointcut-ref="cachePointcut" /> </aop:config>

拓展阅读

Aopalliance 白皮书

Spring AOP

Retry 详解

参考资料

自行编写AOP

AOP 基础知识