核心技術棧
- AOP 配置:XML 命名空間
aop: + tx: 或純註解 @Aspect。
- 動態代理:JDK 接口代理、CGLIB 類代理、Javassist 字節碼操作。
- 緩存提供者:Ehcache(堆/磁盤/分佈式)、頁面片段緩存、Session 緩存。
項目結構
spring-aop-test/
├── src/main/java
│ ├── config/ # AOP、緩存配置類
│ ├── aspect/ # 切面:緩存攔截、日志、事務
│ ├── service/ # 業務邏輯
│ └── dao/ # 數據訪問
└── src/main/resources
├── ehcache.xml # Ehcache 配置
└── applicationContext.xml
關鍵代碼片段
緩存切面(註解版)
@Aspect
@Component
public class CacheAspect {
@Autowired private CacheManager cacheManager;
@Around("@annotation(cached)")
public Object cache(ProceedingJoinPoint pjp, Cached cached) throws Throwable {
String key = buildKey(pjp, cached.key());
Cache cache = cacheManager.getCache(cached.cacheName());
Element element = cache.get(key);
if (element != null) return element.getObjectValue();
Object result = pjp.proceed();
cache.put(new Element(key, result));
return result;
}
}
XML 聲明式事務 + AOP
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceOps" expression="execution(* com.example.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOps"/>
</aop:config>
項目地址
https://github.com/windwant/spring-aop-test