Spring AOP基础组件 Advised

相关阅读

简介

表示被通知的标记接口;
实现子类主要是代理生成的对象和AdvisedSupport

源码

public interface Advised extends TargetClassAware {

    // Advice配置信是否支持修改
    boolean isFrozen();

    // 是否代理指定的类而不是接口
    boolean isProxyTargetClass();

    // 获取代理的接口
    Class<?>[] getProxiedInterfaces();

    // 判断指定接口是否被代理
    boolean isInterfaceProxied(Class<?> intf);

    // 设置代理的目标对象
    void setTargetSource(TargetSource targetSource);

    / 获取代理的目标对象
    TargetSource getTargetSource();

    // 设置是否暴露代理对象到ThreadLocal,方便通过AopContext获取代理对象
    void setExposeProxy(boolean exposeProxy);

    // 判断是否暴露代理对象
    boolean isExposeProxy();

    // 设置是否已预过滤,如果已预过滤,则持有的Advisors都适用
    void setPreFiltered(boolean preFiltered);

    // 判断是否已预过滤
    boolean isPreFiltered();

    // 获取Advisors
    Advisor[] getAdvisors();

    // 获取Advisors数量
    default int getAdvisorCount() {
        return getAdvisors().length;
    }

    // 添加Advisor到链尾
    void addAdvisor(Advisor advisor) throws AopConfigException;

    // 添加Advisor到指定位置,pos必须有效
    void addAdvisor(int pos, Advisor advisor) throws AopConfigException;

    // 移除指定Advisor
    boolean removeAdvisor(Advisor advisor);

    // 移除指定位置的Advisor
    void removeAdvisor(int index) throws AopConfigException;

    // 获取指定Advisor的位置
    int indexOf(Advisor advisor);

    // 替换指定Advisor,如果旧Advisor是引介Advisor,则需要重新获取代理,否则新旧接口都不支持
    boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;

    // 添加Advice到链尾
    void addAdvice(Advice advice) throws AopConfigException;

    // 添加Advice到指定位置,pos必须有效
    void addAdvice(int pos, Advice advice) throws AopConfigException;

    // 移除指定Advice
    boolean removeAdvice(Advice advice);

    // 获取指定Advice的位置
    int indexOf(Advice advice);

    // 获取String形式的ProxyConfig
    String toProxyConfigString();
}

实现子类

public interface Advised extends TargetClassAware
    public class AdvisedSupport extends ProxyConfig implements Advised
        public class ProxyCreatorSupport extends AdvisedSupport
            public class ProxyFactoryBean extends ProxyCreatorSupport implements FactoryBean<Object>, BeanClassLoaderAware, BeanFactoryAware
            public class ProxyFactory extends ProxyCreatorSupport
            public class AspectJProxyFactory extends ProxyCreatorSupport

AdvisedSupport

简介

AOP代理配置管理类的基础类,这些管理类本身不是AOP代理类,但是它们的子类通常是直接获取AOP代理的工厂类;
AdvisedSupport实现了AdviceAdvisor的管理,子类需要负责创建代理;

核心代码

public class AdvisedSupport extends ProxyConfig implements Advised {

    /**
     * Canonical TargetSource when there's no target, and behavior is
     * supplied by the advisors.
     */
    // 目标对象的典例
    public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE;

    // 目标对象
    TargetSource targetSource = EMPTY_TARGET_SOURCE;

    // 预过滤标识
    private boolean preFiltered = false;

    // Advisor链工厂
    AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();

    // 方法缓存,以Method为Key,Advisor chain list为Value
    private transient Map<MethodCacheKey, List<Object>> methodCache;

    // 代理实现的接口集合
    private List<Class<?>> interfaces = new ArrayList<>();

    // Advisor集合
    private List<Advisor> advisors = new ArrayList<>();


    public AdvisedSupport() {
        this.methodCache = new ConcurrentHashMap<>(32);
    }

    public AdvisedSupport(Class<?>... interfaces) {
        this();
        setInterfaces(interfaces);
    }

    public void setTarget(Object target) {
        setTargetSource(new SingletonTargetSource(target));
    }

    @Override
    public void setTargetSource(@Nullable TargetSource targetSource) {
        this.targetSource = (targetSource != null ? targetSource : EMPTY_TARGET_SOURCE);
    }

    @Override
    public TargetSource getTargetSource() {
        return this.targetSource;
    }

    public void setTargetClass(@Nullable Class<?> targetClass) {
        this.targetSource = EmptyTargetSource.forClass(targetClass);
    }

    @Override
    @Nullable
    public Class<?> getTargetClass() {
        return this.targetSource.getTargetClass();
    }

    @Override
    public void setPreFiltered(boolean preFiltered) {
        this.preFiltered = preFiltered;
    }

    @Override
    public boolean isPreFiltered() {
        return this.preFiltered;
    }

    public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) {
        // 校验AdvisorChainFactory
        Assert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null");
        this.advisorChainFactory = advisorChainFactory;
    }

    public AdvisorChainFactory getAdvisorChainFactory() {
        return this.advisorChainFactory;
    }

    public void setInterfaces(Class<?>... interfaces) {
        // 校验代理的接口集合
        Assert.notNull(interfaces, "Interfaces must not be null");
        this.interfaces.clear();
        for (Class<?> ifc : interfaces) {
            addInterface(ifc);
        }
    }

    public void addInterface(Class<?> intf) {
        Assert.notNull(intf, "Interface must not be null");
        if (!intf.isInterface()) {
            // 只支持接口类型
            throw new IllegalArgumentException("[" + intf.getName() + "] is not an interface");
        }
        if (!this.interfaces.contains(intf)) {
            this.interfaces.add(intf);
            adviceChanged();
        }
    }

    public boolean removeInterface(Class<?> intf) {
        return this.interfaces.remove(intf);
    }

    @Override
    public Class<?>[] getProxiedInterfaces() {
        return ClassUtils.toClassArray(this.interfaces);
    }

    @Override
    public boolean isInterfaceProxied(Class<?> intf) {
        // 遍历代理的接口集合
        for (Class<?> proxyIntf : this.interfaces) {
            // 判断指定的接口类型是否属于遍历接口
            if (intf.isAssignableFrom(proxyIntf)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public final Advisor[] getAdvisors() {
        return this.advisors.toArray(new Advisor[0]);
    }

    @Override
    public int getAdvisorCount() {
        return this.advisors.size();
    }

    @Override
    public void addAdvisor(Advisor advisor) {
        int pos = this.advisors.size();
        addAdvisor(pos, advisor);
    }

    @Override
    public void addAdvisor(int pos, Advisor advisor) throws AopConfigException {
        if (advisor instanceof IntroductionAdvisor) {
            // 校验IntroductionAdvisor
            validateIntroductionAdvisor((IntroductionAdvisor) advisor);
        }
        addAdvisorInternal(pos, advisor);
    }

    @Override
    public boolean removeAdvisor(Advisor advisor) {
        int index = indexOf(advisor);
        if (index == -1) {
            return false;
        }
        else {
            removeAdvisor(index);
            return true;
        }
    }

    @Override
    public void removeAdvisor(int index) throws AopConfigException {
        if (isFrozen()) {
            // 不支持变动
            throw new AopConfigException("Cannot remove Advisor: Configuration is frozen.");
        }
        if (index < 0 || index > this.advisors.size() - 1) {
            throw new AopConfigException("Advisor index " + index + " is out of bounds: " +
                    "This configuration only has " + this.advisors.size() + " advisors.");
        }

        Advisor advisor = this.advisors.remove(index);
        if (advisor instanceof IntroductionAdvisor) {
            IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
            // 移除IntroductionAdvisor相关的接口
            for (Class<?> ifc : ia.getInterfaces()) {
                removeInterface(ifc);
            }
        }

        adviceChanged();
    }

    @Override
    public int indexOf(Advisor advisor) {
        Assert.notNull(advisor, "Advisor must not be null");
        return this.advisors.indexOf(advisor);
    }

    @Override
    public boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException {
        Assert.notNull(a, "Advisor a must not be null");
        Assert.notNull(b, "Advisor b must not be null");
        int index = indexOf(a);
        if (index == -1) {
            return false;
        }
        removeAdvisor(index);
        addAdvisor(index, b);
        return true;
    }

    public void addAdvisors(Advisor... advisors) {
        addAdvisors(Arrays.asList(advisors));
    }

    public void addAdvisors(Collection<Advisor> advisors) {
        if (isFrozen()) {
            // 不支持变动
            throw new AopConfigException("Cannot add advisor: Configuration is frozen.");
        }
        if (!CollectionUtils.isEmpty(advisors)) {
            for (Advisor advisor : advisors) {
                if (advisor instanceof IntroductionAdvisor) {
                    validateIntroductionAdvisor((IntroductionAdvisor) advisor);
                }
                Assert.notNull(advisor, "Advisor must not be null");
                this.advisors.add(advisor);
            }
            adviceChanged();
        }
    }

    private void validateIntroductionAdvisor(IntroductionAdvisor advisor) {
        advisor.validateInterfaces();
        // If the advisor passed validation, we can make the change.
        Class<?>[] ifcs = advisor.getInterfaces();
        for (Class<?> ifc : ifcs) {
            addInterface(ifc);
        }
    }

    private void addAdvisorInternal(int pos, Advisor advisor) throws AopConfigException {
        Assert.notNull(advisor, "Advisor must not be null");
        if (isFrozen()) {
            // 不支持变动
            throw new AopConfigException("Cannot add advisor: Configuration is frozen.");
        }
        if (pos > this.advisors.size()) {
            throw new IllegalArgumentException(
                    "Illegal position " + pos + " in advisor list with size " + this.advisors.size());
        }
        this.advisors.add(pos, advisor);
        adviceChanged();
    }

    protected final List<Advisor> getAdvisorsInternal() {
        return this.advisors;
    }

    @Override
    public void addAdvice(Advice advice) throws AopConfigException {
        int pos = this.advisors.size();
        addAdvice(pos, advice);
    }

    @Override
    public void addAdvice(int pos, Advice advice) throws AopConfigException {
        Assert.notNull(advice, "Advice must not be null");
        // 将Advice包装为Advisor
        if (advice instanceof IntroductionInfo) {
            // We don't need an IntroductionAdvisor for this kind of introduction:
            // It's fully self-describing.
            addAdvisor(pos, new DefaultIntroductionAdvisor(advice, (IntroductionInfo) advice));
        }
        else if (advice instanceof DynamicIntroductionAdvice) {
            // We need an IntroductionAdvisor for this kind of introduction.
            throw new AopConfigException("DynamicIntroductionAdvice may only be added as part of IntroductionAdvisor");
        }
        else {
            addAdvisor(pos, new DefaultPointcutAdvisor(advice));
        }
    }

    @Override
    public boolean removeAdvice(Advice advice) throws AopConfigException {
        int index = indexOf(advice);
        if (index == -1) {
            return false;
        }
        else {
            removeAdvisor(index);
            return true;
        }
    }

    @Override
    public int indexOf(Advice advice) {
        Assert.notNull(advice, "Advice must not be null");
        for (int i = 0; i < this.advisors.size(); i++) {
            Advisor advisor = this.advisors.get(i);
            if (advisor.getAdvice() == advice) {
                return i;
            }
        }
        return -1;
    }

    protected void adviceChanged() {
        // 清除方法缓存
        this.methodCache.clear();
    }


    // Method的简单包装类,作为methodCache的Key
    private static final class MethodCacheKey implements Comparable<MethodCacheKey> {

        private final Method method;

        private final int hashCode;

        public MethodCacheKey(Method method) {
            this.method = method;
            this.hashCode = method.hashCode();
        }

        @Override
        public int compareTo(MethodCacheKey other) {
            // 先比较方法名称
            int result = this.method.getName().compareTo(other.method.getName());
            if (result == 0) {
                // 再比较方法签名
                result = this.method.toString().compareTo(other.method.toString());
            }
            return result;
        }
    }
}

ProxyCreatorSupport

简介

代理工厂的基础类,提供对可配置的AopProxyFactory的便捷访问;

核心代码

public class ProxyCreatorSupport extends AdvisedSupport {

    private AopProxyFactory aopProxyFactory;

    private final List<AdvisedSupportListener> listeners = new ArrayList<>();

    // 初始状态未激活,当创建第一个代理对象时设置为true
    private boolean active = false;


    public ProxyCreatorSupport() {
        this.aopProxyFactory = new DefaultAopProxyFactory();
    }

    public ProxyCreatorSupport(AopProxyFactory aopProxyFactory) {
        Assert.notNull(aopProxyFactory, "AopProxyFactory must not be null");
        this.aopProxyFactory = aopProxyFactory;
    }

    protected final synchronized AopProxy createAopProxy() {
        if (!this.active) {
            activate();
        }
        // 通过AopProxyFactory创建代理对象
        return getAopProxyFactory().createAopProxy(this);
    }

    private void activate() {
        this.active = true;
        // 通知激活
        for (AdvisedSupportListener listener : this.listeners) {
            listener.activated(this);
        }
    }

    @Override
    protected void adviceChanged() {
        super.adviceChanged();
        synchronized (this) {
            if (this.active) {
                // 通知变动
                for (AdvisedSupportListener listener : this.listeners) {
                    listener.adviceChanged(this);
                }
            }
        }
    }

    protected final synchronized boolean isActive() {
        return this.active;
    }
}

ProxyFactory

简介

支持自定义获取和配置AOP代理实例的代理实例工厂;

核心代码

public class ProxyFactory extends ProxyCreatorSupport {

    public Object getProxy() {
        // 使用默认地ClassLoader创建代理对象
        return createAopProxy().getProxy();
    }

    public Object getProxy(@Nullable ClassLoader classLoader) {
        // 使用指定的ClassLoader创建代理对象
        return createAopProxy().getProxy(classLoader);
    }

    // 根据指定的接口和拦截器创建代理对象
    @SuppressWarnings("unchecked")
    public static <T> T getProxy(Class<T> proxyInterface, Interceptor interceptor) {
        return (T) new ProxyFactory(proxyInterface, interceptor).getProxy();
    }

    // 根据指定的接口和目标对象创建代理对象
    @SuppressWarnings("unchecked")
    public static <T> T getProxy(Class<T> proxyInterface, TargetSource targetSource) {
        return (T) new ProxyFactory(proxyInterface, targetSource).getProxy();
    }

    // 创建继承自目标对象类型的代理对象
    public static Object getProxy(TargetSource targetSource) {
        if (targetSource.getTargetClass() == null) {
            throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class");
        }
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTargetSource(targetSource);
        proxyFactory.setProxyTargetClass(true);
        return proxyFactory.getProxy();
    }
}

ProxyFactoryBean

简介

基于Spring BeanFactory中的Bean来创建AOP代理实例的FactoryBean的实现;
AdvisorAdvice都是通过bean name指定,最后一个bean name可能是目标对象,但通常目标对象都是通过targetName/target/targetSource属性指定(一旦指定,那么所有bean name只能是Advisor或者Advice);

核心代码

public class ProxyFactoryBean extends ProxyCreatorSupport
        implements FactoryBean<Object>, BeanClassLoaderAware, BeanFactoryAware {

    @Override
    @Nullable
    public Object getObject() throws BeansException {
        initializeAdvisorChain();
        if (isSingleton()) {
            // 单例则会缓存
            return getSingletonInstance();
        }
        else {
            if (this.targetName == null) {
                logger.info("Using non-singleton proxies with singleton targets is often undesirable. " +
                        "Enable prototype proxies by setting the 'targetName' property.");
            }
            // 多例则每次创建新实例
            return newPrototypeInstance();
        }
    }

    private synchronized Object getSingletonInstance() {
        if (this.singletonInstance == null) {
            this.targetSource = freshTargetSource();
            // 自动检测代理的接口
            if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
                // Rely on AOP infrastructure to tell us what interfaces to proxy.
                Class<?> targetClass = getTargetClass();
                if (targetClass == null) {
                    throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
                }
                // 设置代理的接口
                setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
            }
            // Initialize the shared singleton instance.
            super.setFrozen(this.freezeProxy);
            // 创建代理对象
            this.singletonInstance = getProxy(createAopProxy());
        }
        return this.singletonInstance;
    }

    private synchronized Object newPrototypeInstance() {
        // 通过当前配置的拷贝创建代理对象
        ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());

        TargetSource targetSource = freshTargetSource();
        copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());
        if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
            // Rely on AOP infrastructure to tell us what interfaces to proxy.
            Class<?> targetClass = targetSource.getTargetClass();
            if (targetClass != null) {
                copy.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
            }
        }
        copy.setFrozen(this.freezeProxy);

        // 创建代理对象
        return getProxy(copy.createAopProxy());
    }

    protected Object getProxy(AopProxy aopProxy) {
        return aopProxy.getProxy(this.proxyClassLoader);
    }

    @Override
    protected void adviceChanged() {
        super.adviceChanged();
        if (this.singleton) {
            logger.debug("Advice has changed; re-caching singleton instance");
            synchronized (this) {
                // 清除缓存的单例
                this.singletonInstance = null;
            }
        }
    }
}

AspectJProxyFactory

简介

基于AspectJ的代理工厂,支持创建持有AspectJ切面的代理对象;

核心代码

public class AspectJProxyFactory extends ProxyCreatorSupport {

    public void addAspect(Object aspectInstance) {
        Class<?> aspectClass = aspectInstance.getClass();
        String aspectName = aspectClass.getName();
        AspectMetadata am = createAspectMetadata(aspectClass, aspectName);
        if (am.getAjType().getPerClause().getKind() != PerClauseKind.SINGLETON) {
            throw new IllegalArgumentException(
                    "Aspect class [" + aspectClass.getName() + "] does not define a singleton aspect");
        }
        addAdvisorsFromAspectInstanceFactory(
                new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, aspectName));
    }

    public void addAspect(Class<?> aspectClass) {
        String aspectName = aspectClass.getName();
        AspectMetadata am = createAspectMetadata(aspectClass, aspectName);
        MetadataAwareAspectInstanceFactory instanceFactory = createAspectInstanceFactory(am, aspectClass, aspectName);
        addAdvisorsFromAspectInstanceFactory(instanceFactory);
    }

    private void addAdvisorsFromAspectInstanceFactory(MetadataAwareAspectInstanceFactory instanceFactory) {
        List<Advisor> advisors = this.aspectFactory.getAdvisors(instanceFactory);
        Class<?> targetClass = getTargetClass();
        Assert.state(targetClass != null, "Unresolvable target class");
        advisors = AopUtils.findAdvisorsThatCanApply(advisors, targetClass);
        AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(advisors);
        AnnotationAwareOrderComparator.sort(advisors);
        addAdvisors(advisors);
    }

    private AspectMetadata createAspectMetadata(Class<?> aspectClass, String aspectName) {
        AspectMetadata am = new AspectMetadata(aspectClass, aspectName);
        if (!am.getAjType().isAspect()) {
            throw new IllegalArgumentException("Class [" + aspectClass.getName() + "] is not a valid aspect type");
        }
        return am;
    }

    private MetadataAwareAspectInstanceFactory createAspectInstanceFactory(
            AspectMetadata am, Class<?> aspectClass, String aspectName) {

        MetadataAwareAspectInstanceFactory instanceFactory;
        if (am.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
            // Create a shared aspect instance.
            Object instance = getSingletonAspectInstance(aspectClass);
            instanceFactory = new SingletonMetadataAwareAspectInstanceFactory(instance, aspectName);
        }
        else {
            // Create a factory for independent aspect instances.
            instanceFactory = new SimpleMetadataAwareAspectInstanceFactory(aspectClass, aspectName);
        }
        return instanceFactory;
    }

    private Object getSingletonAspectInstance(Class<?> aspectClass) {
        return aspectCache.computeIfAbsent(aspectClass,
                clazz -> new SimpleAspectInstanceFactory(clazz).getAspectInstance());
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxy() {
        return (T) createAopProxy().getProxy();
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxy(ClassLoader classLoader) {
        return (T) createAopProxy().getProxy(classLoader);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值