首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring AOP 實戰:動態代理實現聲明式緩存

     編輯:Java 綜合教學

核心技術棧

  • 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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved