IntroductionAdvisor切面使用案例

理解 IntroductionAdvisor的关键在于认识到它是 Spring AOP 中一种改变类结构的特殊增强方式。与常规的 PointcutAdvisor(在方法调用前后插入逻辑)不同,IntroductionAdvisor是为目标类动态添加新接口实现的能力。

引介切面和切点切面对比

在这里插入图片描述

如何使用

IntroductionAdvisor一个是类结构增强, PointcutAdvisor是方法调用时的增强。

案例:给业务类,增加缓存能力

// 1、业务类
@Service
public class ProductService {
    // 原本没有缓存能力
    public Product getProduct(String id) {
        // 数据库查询
    }
}


// 缓存能力接口
public interface Cacheable {
    void cacheResult(String key, Object value);
    Object getCached(String key);
}
// 缓存能力实现逻辑
public class CacheableImpl implements Cacheable {
    private Map<String, Object> cache = new ConcurrentHashMap<>();
    
    public void cacheResult(String key, Object value) {
        cache.put(key, value);
    }
    
    public Object getCached(String key) {
        return cache.get(key);
    }
}


// 创建引介切面Advisor,让缓存和业务类建立绑定关系。
public class CacheableAdvisor extends DefaultIntroductionAdvisor {
    public CacheableAdvisor() {
        super(new CacheableImpl(), Cacheable.class);
    }

    // 指定哪些类需要增强
    @Override
    public ClassFilter getClassFilter() {
        return clazz -> ProductService.class.isAssignableFrom(clazz);
    }

    //这2个方法就是让Cacheable和ProductService建立关系。
}


// 使用增强后的ProductService
ProductService service = ...;
Cacheable cacheable = (Cacheable) service; // 强制转换
cacheable.cacheResult("p123", product);

生成的代理对象

// Spring生成的代理类(概念模型)  包含:继承原始类(ProductService)+实现引入的接口(Cacheable)
public class ProductService$$EnhancerBySpringCGLIB extends ProductService implements Cacheable, SpringProxy {
    
    // 委托对象
    private Cacheable cacheDelegate = new CacheableImpl();
    
    // 实现Cacheable接口
    public void cacheResult(String key, Object value) {
        cacheDelegate.cacheResult(key, value);
    }
    
    public Object getCached(String key) {
        return cacheDelegate.getCached(key);
    }
    
    // 原始方法(可能被增强)
    public Product getProduct(String id) {
        return super.getProduct(id);
    }
}

使用场景

租户上下文传递,比如在Controller统一获取shareId

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信仰_273993243

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值