org.springframework.aop.TargetSource

Here are the examples of the java api org.springframework.aop.TargetSource taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

68 Examples 7

19 View Source File : ClassUtil.java
License : Apache License 2.0
Project Creator : yametech

/**
 * 参考spring-aop
 *
 * @param candidate
 * @return
 */
public static Clreplaced<?> getJDKTargetClreplaced(Object candidate) {
    Object current = candidate;
    Clreplaced<?> result = null;
    while (current instanceof TargetClreplacedAware) {
        result = ((TargetClreplacedAware) current).getTargetClreplaced();
        Object nested = null;
        if (current instanceof Advised) {
            TargetSource targetSource = ((Advised) current).getTargetSource();
            if (targetSource instanceof SingletonTargetSource) {
                nested = ((SingletonTargetSource) targetSource).getTarget();
            }
        }
        current = nested;
    }
    return result;
}

19 View Source File : MBeanServerConnectionFactoryBean.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Creates lazy proxies for the {@code JMXConnector} and {@code MBeanServerConnection}.
 */
private void createLazyConnection() {
    this.connectorTargetSource = new JMXConnectorLazyInitTargetSource();
    TargetSource connectionTargetSource = new MBeanServerConnectionLazyInitTargetSource();
    this.connector = (JMXConnector) new ProxyFactory(JMXConnector.clreplaced, this.connectorTargetSource).getProxy(this.beanClreplacedLoader);
    this.connection = (MBeanServerConnection) new ProxyFactory(MBeanServerConnection.clreplaced, connectionTargetSource).getProxy(this.beanClreplacedLoader);
}

19 View Source File : ProxyFactoryBean.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create a new prototype instance of this clreplaced's created proxy object,
 * backed by an independent AdvisedSupport configuration.
 * @return a totally independent proxy, whose advice we may manipulate in isolation
 */
private synchronized Object newPrototypeInstance() {
    // In the case of a prototype, we need to give the proxy
    // an independent instance of the configuration.
    // In this case, no proxy will have an instance of this object's configuration,
    // but will have an independent copy.
    if (logger.isTraceEnabled()) {
        logger.trace("Creating copy of prototype ProxyFactoryBean config: " + this);
    }
    ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());
    // The copy needs a fresh advisor chain, and a fresh TargetSource.
    TargetSource targetSource = freshTargetSource();
    copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());
    if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClreplaced()) {
        // Rely on AOP infrastructure to tell us what interfaces to proxy.
        Clreplaced<?> targetClreplaced = targetSource.getTargetClreplaced();
        if (targetClreplaced != null) {
            copy.setInterfaces(ClreplacedUtils.getAllInterfacesForClreplaced(targetClreplaced, this.proxyClreplacedLoader));
        }
    }
    copy.setFrozen(this.freezeProxy);
    if (logger.isTraceEnabled()) {
        logger.trace("Using ProxyCreatorSupport copy: " + copy);
    }
    return getProxy(copy.createAopProxy());
}

19 View Source File : ProxyFactory.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create a proxy for the specified {@code TargetSource} that extends
 * the target clreplaced of the {@code TargetSource}.
 * @param targetSource the TargetSource that the proxy should invoke
 * @return the proxy object
 */
public static Object getProxy(TargetSource targetSource) {
    if (targetSource.getTargetClreplaced() == null) {
        throw new IllegalArgumentException("Cannot create clreplaced proxy for TargetSource with null target clreplaced");
    }
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTargetSource(targetSource);
    proxyFactory.setProxyTargetClreplaced(true);
    return proxyFactory.getProxy();
}

19 View Source File : AbstractAutoProxyCreator.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create a target source for bean instances. Uses any TargetSourceCreators if set.
 * Returns {@code null} if no custom TargetSource should be used.
 * <p>This implementation uses the "customTargetSourceCreators" property.
 * Subclreplacedes can override this method to use a different mechanism.
 * @param beanClreplaced the clreplaced of the bean to create a TargetSource for
 * @param beanName the name of the bean
 * @return a TargetSource for this bean
 * @see #setCustomTargetSourceCreators
 */
@Nullable
protected TargetSource getCustomTargetSource(Clreplaced<?> beanClreplaced, String beanName) {
    // We can't create fancy target sources for directly registered singletons.
    if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
        for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
            TargetSource ts = tsc.getTargetSource(beanClreplaced, beanName);
            if (ts != null) {
                // Found a matching TargetSource.
                if (logger.isTraceEnabled()) {
                    logger.trace("TargetSourceCreator [" + tsc + "] found custom TargetSource for bean with name '" + beanName + "'");
                }
                return ts;
            }
        }
    }
    // No custom TargetSource found.
    return null;
}

19 View Source File : AopProxyUtils.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Obtain the singleton target object behind the given proxy, if any.
 * @param candidate the (potential) proxy to check
 * @return the singleton target object managed in a {@link SingletonTargetSource},
 * or {@code null} in any other case (not a proxy, not an existing singleton target)
 * @since 4.3.8
 * @see Advised#getTargetSource()
 * @see SingletonTargetSource#getTarget()
 */
@Nullable
public static Object getSingletonTarget(Object candidate) {
    if (candidate instanceof Advised) {
        TargetSource targetSource = ((Advised) candidate).getTargetSource();
        if (targetSource instanceof SingletonTargetSource) {
            return ((SingletonTargetSource) targetSource).getTarget();
        }
    }
    return null;
}

19 View Source File : AdvisedSupport.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Copy the AOP configuration from the given AdvisedSupport object,
 * but allow subsreplacedution of a fresh TargetSource and a given interceptor chain.
 * @param other the AdvisedSupport object to take proxy configuration from
 * @param targetSource the new TargetSource
 * @param advisors the Advisors for the chain
 */
protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List<Advisor> advisors) {
    copyFrom(other);
    this.targetSource = targetSource;
    this.advisorChainFactory = other.advisorChainFactory;
    this.interfaces = new ArrayList<>(other.interfaces);
    for (Advisor advisor : advisors) {
        if (advisor instanceof IntroductionAdvisor) {
            validateIntroductionAdvisor((IntroductionAdvisor) advisor);
        }
        replacedert.notNull(advisor, "Advisor must not be null");
        this.advisors.add(advisor);
    }
    updateAdvisorArray();
    adviceChanged();
}

19 View Source File : AdvisedSupport.java
License : MIT License
Project Creator : Vip-Augus

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

19 View Source File : BeanFactoryUtils.java
License : Apache License 2.0
Project Creator : spring-projects-experimental

public static <T> T lazy(Clreplaced<T> type, Supplier<T> supplier) {
    TargetSource ts = new TargetSource() {

        @Override
        public Clreplaced<?> getTargetClreplaced() {
            return type;
        }

        @Override
        public boolean isStatic() {
            return false;
        }

        @Override
        public Object getTarget() {
            Object target = supplier.get();
            if (target == null) {
                Clreplaced<?> type = getTargetClreplaced();
                if (Map.clreplaced == type) {
                    return Collections.emptyMap();
                } else if (List.clreplaced == type) {
                    return Collections.emptyList();
                } else if (Set.clreplaced == type || Collection.clreplaced == type) {
                    return Collections.emptySet();
                }
                throw new NoSuchBeanDefinitionException(type, "Optional dependency not present for lazy injection point");
            }
            return target;
        }

        @Override
        public void releaseTarget(Object target) {
        }
    };
    ProxyFactory pf = new ProxyFactory();
    pf.setTargetSource(ts);
    pf.addInterface(type);
    @SuppressWarnings("unchecked")
    T proxy = (T) pf.getProxy();
    return proxy;
}

19 View Source File : DelayQueueScaner.java
License : Apache License 2.0
Project Creator : spring-avengers

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced<?> beanClreplaced, String beanName, TargetSource customTargetSource) throws BeansException {
    return new Object[] { interceptor };
}

19 View Source File : AbstractAutoProxyCreator.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Create a target source for bean instances. Uses any TargetSourceCreators if set. Returns
 * {@code null} if no custom TargetSource should be used.
 * <p>This implementation uses the "customTargetSourceCreators" property.
 * Subclreplacedes can override this method to use a different mechanism.
 *
 * @param beanClreplaced the clreplaced of the bean to create a TargetSource for
 * @param beanName  the name of the bean
 *
 * @return a TargetSource for this bean
 *
 * @see #setCustomTargetSourceCreators
 */
@Nullable
protected TargetSource getCustomTargetSource(Clreplaced<?> beanClreplaced, String beanName) {
    // We can't create fancy target sources for directly registered singletons.
    if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
        for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
            TargetSource ts = tsc.getTargetSource(beanClreplaced, beanName);
            if (ts != null) {
                // Found a matching TargetSource.
                if (logger.isTraceEnabled()) {
                    logger.trace("TargetSourceCreator [" + tsc + "] found custom TargetSource for bean with name '" + beanName + "'");
                }
                return ts;
            }
        }
    }
    // No custom TargetSource found.
    return null;
}

19 View Source File : AdvisedSupport.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Copy the AOP configuration from the given AdvisedSupport object, but allow subsreplacedution of a
 * fresh TargetSource and a given interceptor chain.
 *
 * @param other        the AdvisedSupport object to take proxy configuration from
 * @param targetSource the new TargetSource
 * @param advisors     the Advisors for the chain
 */
protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List<Advisor> advisors) {
    copyFrom(other);
    this.targetSource = targetSource;
    this.advisorChainFactory = other.advisorChainFactory;
    this.interfaces = new ArrayList<>(other.interfaces);
    for (Advisor advisor : advisors) {
        if (advisor instanceof IntroductionAdvisor) {
            validateIntroductionAdvisor((IntroductionAdvisor) advisor);
        }
        replacedert.notNull(advisor, "Advisor must not be null");
        this.advisors.add(advisor);
    }
    updateAdvisorArray();
    adviceChanged();
}

19 View Source File : GlobalTransactionScanner.java
License : Apache License 2.0
Project Creator : seata

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced beanClreplaced, String beanName, TargetSource customTargetSource) throws BeansException {
    return new Object[] { interceptor };
}

19 View Source File : AbstractAnnotationEnhancer.java
License : Apache License 2.0
Project Creator : RabbitOpen

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced<?> beanClreplaced, String beanName, TargetSource customTargetSource) {
    if (beans2Enhance.contains(beanName)) {
        return getPointCuts();
    }
    return DO_NOT_PROXY;
}

19 View Source File : AopProxyUtils.java
License : Apache License 2.0
Project Creator : leiyong0326

/**
 * 是否代理了多次
 * see http://jinnianshilongnian.iteye.com/blog/1894465
 * @param proxy
 * @return
 */
public static boolean isMultipleProxy(Object proxy) {
    try {
        ProxyFactory proxyFactory = null;
        if (AopUtils.isJdkDynamicProxy(proxy)) {
            proxyFactory = findJdkDynamicProxyFactory(proxy);
        }
        if (AopUtils.isCglibProxy(proxy)) {
            proxyFactory = findCglibProxyFactory(proxy);
        }
        TargetSource targetSource = (TargetSource) ReflectionUtils.getField(ProxyFactory_targetSource_FIELD, proxyFactory);
        return AopUtils.isAopProxy(targetSource.getTarget());
    } catch (Exception e) {
        throw new IllegalArgumentException("proxy args maybe not proxy with cglib or jdk dynamic proxy. this method not support", e);
    }
}

19 View Source File : MBeanServerConnectionFactoryBean.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Creates lazy proxies for the {@code JMXConnector} and {@code MBeanServerConnection}
 */
private void createLazyConnection() {
    this.connectorTargetSource = new JMXConnectorLazyInitTargetSource();
    TargetSource connectionTargetSource = new MBeanServerConnectionLazyInitTargetSource();
    this.connector = (JMXConnector) new ProxyFactory(JMXConnector.clreplaced, this.connectorTargetSource).getProxy(this.beanClreplacedLoader);
    this.connection = (MBeanServerConnection) new ProxyFactory(MBeanServerConnection.clreplaced, connectionTargetSource).getProxy(this.beanClreplacedLoader);
}

19 View Source File : ProxyFactoryBean.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Create a new prototype instance of this clreplaced's created proxy object,
 * backed by an independent AdvisedSupport configuration.
 * @return a totally independent proxy, whose advice we may manipulate in isolation
 */
private synchronized Object newPrototypeInstance() {
    // In the case of a prototype, we need to give the proxy
    // an independent instance of the configuration.
    // In this case, no proxy will have an instance of this object's configuration,
    // but will have an independent copy.
    if (logger.isTraceEnabled()) {
        logger.trace("Creating copy of prototype ProxyFactoryBean config: " + this);
    }
    ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());
    // The copy needs a fresh advisor chain, and a fresh TargetSource.
    TargetSource targetSource = freshTargetSource();
    copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());
    if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClreplaced()) {
        // Rely on AOP infrastructure to tell us what interfaces to proxy.
        copy.setInterfaces(ClreplacedUtils.getAllInterfacesForClreplaced(targetSource.getTargetClreplaced(), this.proxyClreplacedLoader));
    }
    copy.setFrozen(this.freezeProxy);
    if (logger.isTraceEnabled()) {
        logger.trace("Using ProxyCreatorSupport copy: " + copy);
    }
    return getProxy(copy.createAopProxy());
}

19 View Source File : AbstractAutoProxyCreator.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Create a target source for bean instances. Uses any TargetSourceCreators if set.
 * Returns {@code null} if no custom TargetSource should be used.
 * <p>This implementation uses the "customTargetSourceCreators" property.
 * Subclreplacedes can override this method to use a different mechanism.
 * @param beanClreplaced the clreplaced of the bean to create a TargetSource for
 * @param beanName the name of the bean
 * @return a TargetSource for this bean
 * @see #setCustomTargetSourceCreators
 */
protected TargetSource getCustomTargetSource(Clreplaced<?> beanClreplaced, String beanName) {
    // We can't create fancy target sources for directly registered singletons.
    if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
        for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
            TargetSource ts = tsc.getTargetSource(beanClreplaced, beanName);
            if (ts != null) {
                // Found a matching TargetSource.
                if (logger.isDebugEnabled()) {
                    logger.debug("TargetSourceCreator [" + tsc + " found custom TargetSource for bean with name '" + beanName + "'");
                }
                return ts;
            }
        }
    }
    // No custom TargetSource found.
    return null;
}

19 View Source File : AdvisedSupport.java
License : Apache License 2.0
Project Creator : langtianya

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

19 View Source File : AdvisedSupport.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Copy the AOP configuration from the given AdvisedSupport object,
 * but allow subsreplacedution of a fresh TargetSource and a given interceptor chain.
 * @param other the AdvisedSupport object to take proxy configuration from
 * @param targetSource the new TargetSource
 * @param advisors the Advisors for the chain
 */
protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List<Advisor> advisors) {
    copyFrom(other);
    this.targetSource = targetSource;
    this.advisorChainFactory = other.advisorChainFactory;
    this.interfaces = new ArrayList<Clreplaced<?>>(other.interfaces);
    for (Advisor advisor : advisors) {
        if (advisor instanceof IntroductionAdvisor) {
            validateIntroductionAdvisor((IntroductionAdvisor) advisor);
        }
        replacedert.notNull(advisor, "Advisor must not be null");
        this.advisors.add(advisor);
    }
    updateAdvisorArray();
    adviceChanged();
}

19 View Source File : EagleTraceAutoProxyCreator.java
License : Apache License 2.0
Project Creator : fang-yan-peng

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced<?> aClreplaced, String s, TargetSource targetSource) throws BeansException {
    if (!needTrace(aClreplaced)) {
        return DO_NOT_PROXY;
    }
    return new Object[0];
}

19 View Source File : EagleTraceAutoProxyCreator.java
License : Apache License 2.0
Project Creator : fang-yan-peng

private void injectRefer(final Clreplaced<?> beanClreplaced, final TargetSource bean) {
    try {
        ReflectionUtils.doWithFields(beanClreplaced, new ReflectionUtils.FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                Refer refer = field.getAnnotation(Refer.clreplaced);
                ReflectionUtils.makeAccessible(field);
                String id = ReferContext.getName(refer, field.getType());
                if (!Strings.isNullOrEmpty(id)) {
                    try {
                        field.set(bean.getTarget(), ctx.getBean(id));
                    } catch (Exception e) {
                        throw new IllegalStateException(e);
                    }
                }
            }
        }, new ReflectionUtils.FieldFilter() {

            @Override
            public boolean matches(Field field) {
                return field.isAnnotationPresent(Refer.clreplaced);
            }
        });
    } catch (Throwable e) {
    }
}

18 View Source File : ScriptFactoryPostProcessor.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create a refreshable proxy for the given AOP TargetSource.
 * @param ts the refreshable TargetSource
 * @param interfaces the proxy interfaces (may be {@code null} to
 * indicate proxying of all interfaces implemented by the target clreplaced)
 * @return the generated proxy
 * @see RefreshableScriptTargetSource
 */
protected Object createRefreshableProxy(TargetSource ts, @Nullable Clreplaced<?>[] interfaces, boolean proxyTargetClreplaced) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTargetSource(ts);
    ClreplacedLoader clreplacedLoader = this.beanClreplacedLoader;
    if (interfaces != null) {
        proxyFactory.setInterfaces(interfaces);
    } else {
        Clreplaced<?> targetClreplaced = ts.getTargetClreplaced();
        if (targetClreplaced != null) {
            proxyFactory.setInterfaces(ClreplacedUtils.getAllInterfacesForClreplaced(targetClreplaced, this.beanClreplacedLoader));
        }
    }
    if (proxyTargetClreplaced) {
        // force use of Clreplaced.getClreplacedLoader()
        clreplacedLoader = null;
        proxyFactory.setProxyTargetClreplaced(true);
    }
    DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(ts);
    introduction.suppressInterface(TargetSource.clreplaced);
    proxyFactory.addAdvice(introduction);
    return proxyFactory.getProxy(clreplacedLoader);
}

18 View Source File : CommonAnnotationBeanPostProcessor.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Obtain a lazily resolving resource proxy for the given name and type,
 * delegating to {@link #getResource} on demand once a method call comes in.
 * @param element the descriptor for the annotated field/method
 * @param requestingBeanName the name of the requesting bean
 * @return the resource object (never {@code null})
 * @since 4.2
 * @see #getResource
 * @see Lazy
 */
protected Object buildLazyResourceProxy(final LookupElement element, @Nullable final String requestingBeanName) {
    TargetSource ts = new TargetSource() {

        @Override
        public Clreplaced<?> getTargetClreplaced() {
            return element.lookupType;
        }

        @Override
        public boolean isStatic() {
            return false;
        }

        @Override
        public Object getTarget() {
            return getResource(element, requestingBeanName);
        }

        @Override
        public void releaseTarget(Object target) {
        }
    };
    ProxyFactory pf = new ProxyFactory();
    pf.setTargetSource(ts);
    if (element.lookupType.isInterface()) {
        pf.addInterface(element.lookupType);
    }
    ClreplacedLoader clreplacedLoader = (this.beanFactory instanceof ConfigurableBeanFactory ? ((ConfigurableBeanFactory) this.beanFactory).getBeanClreplacedLoader() : null);
    return pf.getProxy(clreplacedLoader);
}

18 View Source File : ProxyFactory.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create a proxy for the specified {@code TargetSource},
 * implementing the specified interface.
 * @param proxyInterface the interface that the proxy should implement
 * @param targetSource the TargetSource that the proxy should invoke
 * @return the proxy object
 * @see #ProxyFactory(Clreplaced, org.springframework.aop.TargetSource)
 */
@SuppressWarnings("unchecked")
public static <T> T getProxy(Clreplaced<T> proxyInterface, TargetSource targetSource) {
    return (T) new ProxyFactory(proxyInterface, targetSource).getProxy();
}

18 View Source File : AbstractAutoProxyCreator.java
License : MIT License
Project Creator : Vip-Augus

@Override
public Object postProcessBeforeInstantiation(Clreplaced<?> beanClreplaced, String beanName) {
    // 注释 8. 切面 bean 实例化之前执行的方法
    // 根据 beanClreplaced 或者 beanName,组装一个 唯一 key
    Object cacheKey = getCacheKey(beanClreplaced, beanName);
    // beanName 不存在 || 目标堆中不存在这个 bean
    if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
        // 内层判断是否需要进行切面增强,这是个短路操作,判断成功后将跳过后面的操作
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        if (isInfrastructureClreplaced(beanClreplaced) || shouldSkip(beanClreplaced, beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return null;
        }
    }
    // Create proxy here if we have a custom TargetSource.
    // Suppresses unnecessary default instantiation of the target bean:
    // The TargetSource will handle target instances in a custom fashion.
    // 如果我们有自定义 TargetSource,请在此处创建代理。
    // 禁止目标bean的不必要的默认实例化:
    // TargetSource将以自定义方式处理目标实例
    TargetSource targetSource = getCustomTargetSource(beanClreplaced, beanName);
    if (targetSource != null) {
        if (StringUtils.hasLength(beanName)) {
            this.targetSourcedBeans.add(beanName);
        }
        // 实际上委派给子类去实现 AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClreplaced, beanName, targetSource);
        // 根据上面的增强方法创建代理
        Object proxy = createProxy(beanClreplaced, beanName, specificInterceptors, targetSource);
        this.proxyTypes.put(cacheKey, proxy.getClreplaced());
        return proxy;
    }
    return null;
}

18 View Source File : AbstractAutoProxyCreator.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create an AOP proxy for the given bean.
 *
 * 注释 8.9 为给定的bean创建AOP代理,实际在这一步中进行切面织入,生成动态代理
 *
 * @param beanClreplaced the clreplaced of the bean
 * @param beanName the name of the bean
 * @param specificInterceptors the set of interceptors that is
 * specific to this bean (may be empty, but not null)
 * @param targetSource the TargetSource for the proxy,
 * already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Clreplaced<?> beanClreplaced, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClreplaced((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClreplaced);
    }
    ProxyFactory proxyFactory = new ProxyFactory();
    // 拷贝,获取当前类中的相关属性
    proxyFactory.copyFrom(this);
    // 决定对于给定 bean 是否应该使用 targetClreplaced 而不是他的接口代理
    if (!proxyFactory.isProxyTargetClreplaced()) {
        // 检查 proxyTargetClreplaced 设置以及 preserveTargetClreplaced 属性
        if (shouldProxyTargetClreplaced(beanClreplaced, beanName)) {
            proxyFactory.setProxyTargetClreplaced(true);
        } else {
            // 添加代理接口
            evaluateProxyInterfaces(beanClreplaced, proxyFactory);
        }
    }
    // 这一步中,主要将拦截器封装为增强器
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    proxyFactory.addAdvisors(advisors);
    proxyFactory.setTargetSource(targetSource);
    // 定制代理
    customizeProxyFactory(proxyFactory);
    // 用来控制代理工厂被配置之后,是否含允许修改通知
    // 缺省值为 false,不允许修改代理的配置
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    // 生成代理,委托给了 ProxyFactory 去处理。
    return proxyFactory.getProxy(getProxyClreplacedLoader());
}

18 View Source File : EclairProxyCreator.java
License : Apache License 2.0
Project Creator : TinkoffCreditSystems

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced<?> beanClreplaced, String beanName, TargetSource customTargetSource) throws BeansException {
    Clreplaced<?> targetClreplaced = beanClreplacedCache.computeIfAbsent(beanName, s -> ClreplacedUtils.getUserClreplaced(beanClreplaced));
    Object[] cachedAdvisors = advisorsCache.get(targetClreplaced);
    if (nonNull(cachedAdvisors)) {
        return cachedAdvisors.length == 0 ? AbstractAutoProxyCreator.DO_NOT_PROXY : cachedAdvisors;
    }
    if (!supports(targetClreplaced)) {
        advisorsCache.put(targetClreplaced, EMPTY_ARRAY);
        return AbstractAutoProxyCreator.DO_NOT_PROXY;
    }
    if (validate) {
        annotationExtractor.getCandidateMethods(targetClreplaced).forEach(methodValidator::validate);
    }
    MdcAdvisor mdcAdvisor = getMdcAdvisor(targetClreplaced);
    List<LogAdvisor> logAdvisors = getLoggingAdvisors(targetClreplaced);
    Object[] composedAdvisors = composeAdvisors(mdcAdvisor, logAdvisors);
    advisorsCache.put(targetClreplaced, composedAdvisors);
    return composedAdvisors.length == 0 ? AbstractAutoProxyCreator.DO_NOT_PROXY : composedAdvisors;
}

18 View Source File : LazyCreationTargetSourceTests.java
License : Apache License 2.0
Project Creator : SourceHot

@Test
public void testCreateLazy() {
    TargetSource targetSource = new AbstractLazyCreationTargetSource() {

        @Override
        protected Object createObject() {
            return new InitCountingBean();
        }

        @Override
        public Clreplaced<?> getTargetClreplaced() {
            return InitCountingBean.clreplaced;
        }
    };
    InitCountingBean proxy = (InitCountingBean) ProxyFactory.getProxy(targetSource);
    replacedertThat(InitCountingBean.initCount).as("Init count should be 0").isEqualTo(0);
    replacedertThat(targetSource.getTargetClreplaced()).as("Target clreplaced incorrect").isEqualTo(InitCountingBean.clreplaced);
    replacedertThat(InitCountingBean.initCount).as("Init count should still be 0 after getTargetClreplaced()").isEqualTo(0);
    proxy.doSomething();
    replacedertThat(InitCountingBean.initCount).as("Init count should now be 1").isEqualTo(1);
    proxy.doSomething();
    replacedertThat(InitCountingBean.initCount).as("Init count should still be 1").isEqualTo(1);
}

18 View Source File : AbstractAutoProxyCreator.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * 后置方法
 *
 * @param beanClreplaced the clreplaced of the bean to be instantiated
 * @param beanName  the name of the bean
 *
 * @return
 */
@Override
public Object postProcessBeforeInstantiation(Clreplaced<?> beanClreplaced, String beanName) {
    Object cacheKey = getCacheKey(beanClreplaced, beanName);
    if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        if (isInfrastructureClreplaced(beanClreplaced) || shouldSkip(beanClreplaced, beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return null;
        }
    }
    // Create proxy here if we have a custom TargetSource.
    // Suppresses unnecessary default instantiation of the target bean:
    // The TargetSource will handle target instances in a custom fashion.
    TargetSource targetSource = getCustomTargetSource(beanClreplaced, beanName);
    if (targetSource != null) {
        if (StringUtils.hasLength(beanName)) {
            this.targetSourcedBeans.add(beanName);
        }
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClreplaced, beanName, targetSource);
        Object proxy = createProxy(beanClreplaced, beanName, specificInterceptors, targetSource);
        this.proxyTypes.put(cacheKey, proxy.getClreplaced());
        return proxy;
    }
    return null;
}

18 View Source File : AbstractAutoProxyCreator.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Create an AOP proxy for the given bean.
 *
 * @param beanClreplaced            the clreplaced of the bean
 * @param beanName             the name of the bean
 * @param specificInterceptors the set of interceptors that is specific to this bean (may be
 *                             empty, but not null) 增强方法
 * @param targetSource         the TargetSource for the proxy, already pre-configured to access
 *                             the bean
 *
 * @return the AOP proxy for the bean
 *
 * @see #buildAdvisors
 */
protected Object createProxy(Clreplaced<?> beanClreplaced, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClreplaced((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClreplaced);
    }
    // 对象拷贝
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);
    if (!proxyFactory.isProxyTargetClreplaced()) {
        if (shouldProxyTargetClreplaced(beanClreplaced, beanName)) {
            proxyFactory.setProxyTargetClreplaced(true);
        } else {
            evaluateProxyInterfaces(beanClreplaced, proxyFactory);
        }
    }
    // 增强器构造
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    proxyFactory.addAdvisors(advisors);
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    return proxyFactory.getProxy(getProxyClreplacedLoader());
}

18 View Source File : FactoryBeanPostProcessor.java
License : Apache License 2.0
Project Creator : sofastack

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced<?> beanClreplaced, String beanName, TargetSource customTargetSource) throws BeansException {
    return new Object[0];
}

18 View Source File : DAOTypeAutoProxyCreator.java
License : GNU Affero General Public License v3.0
Project Creator : qlangtech

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced<?> beanClreplaced, String beanName, TargetSource customTargetSource) throws BeansException {
    if (beanClreplaced == null || beanClreplaced.getPackage() == null) {
        return DO_NOT_PROXY;
    }
    try {
        if (beanClreplaced.equals(com.qlangtech.tis.manage.biz.dal.dao.impl.OperationLogDAOImpl.clreplaced) || IDepartmentDAO.clreplaced.isreplacedignableFrom(beanClreplaced)) {
            return DO_NOT_PROXY;
        }
    } catch (Exception e) {
        throw new BeansException(e.getMessage(), e) {

            private static final long serialVersionUID = 1L;
        };
    }
    return ((com.qlangtech.tis.manage.common.OperationLogger.clreplaced.isreplacedignableFrom(beanClreplaced))) ? PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS : DO_NOT_PROXY;
}

18 View Source File : AbstractAutoProxyCreator.java
License : MIT License
Project Creator : mindcarver

@Override
public Object postProcessBeforeInstantiation(Clreplaced<?> beanClreplaced, String beanName) {
    Object cacheKey = getCacheKey(beanClreplaced, beanName);
    if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        if (isInfrastructureClreplaced(beanClreplaced) || shouldSkip(beanClreplaced, beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return null;
        }
    }
    // Create proxy here if we have a custom TargetSource.
    // Suppresses unnecessary default instantiation of the target bean:
    // The TargetSource will handle target instances in a custom fashion.
    TargetSource targetSource = getCustomTargetSource(beanClreplaced, beanName);
    if (targetSource != null) {
        if (StringUtils.hasLength(beanName)) {
            this.targetSourcedBeans.add(beanName);
        }
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClreplaced, beanName, targetSource);
        Object proxy = createProxy(beanClreplaced, beanName, specificInterceptors, targetSource);
        this.proxyTypes.put(cacheKey, proxy.getClreplaced());
        return proxy;
    }
    return null;
}

18 View Source File : AbstractAutoProxyCreator.java
License : MIT License
Project Creator : mindcarver

/**
 * Create an AOP proxy for the given bean.
 * @param beanClreplaced the clreplaced of the bean
 * @param beanName the name of the bean
 * @param specificInterceptors the set of interceptors that is
 * specific to this bean (may be empty, but not null)
 * @param targetSource the TargetSource for the proxy,
 * already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Clreplaced<?> beanClreplaced, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClreplaced((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClreplaced);
    }
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);
    if (!proxyFactory.isProxyTargetClreplaced()) {
        if (shouldProxyTargetClreplaced(beanClreplaced, beanName)) {
            proxyFactory.setProxyTargetClreplaced(true);
        } else {
            evaluateProxyInterfaces(beanClreplaced, proxyFactory);
        }
    }
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    proxyFactory.addAdvisors(advisors);
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    return proxyFactory.getProxy(getProxyClreplacedLoader());
}

18 View Source File : ScriptFactoryPostProcessor.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Create a refreshable proxy for the given AOP TargetSource.
 * @param ts the refreshable TargetSource
 * @param interfaces the proxy interfaces (may be {@code null} to
 * indicate proxying of all interfaces implemented by the target clreplaced)
 * @return the generated proxy
 * @see RefreshableScriptTargetSource
 */
protected Object createRefreshableProxy(TargetSource ts, Clreplaced<?>[] interfaces, boolean proxyTargetClreplaced) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTargetSource(ts);
    ClreplacedLoader clreplacedLoader = this.beanClreplacedLoader;
    if (interfaces == null) {
        interfaces = ClreplacedUtils.getAllInterfacesForClreplaced(ts.getTargetClreplaced(), this.beanClreplacedLoader);
    }
    proxyFactory.setInterfaces(interfaces);
    if (proxyTargetClreplaced) {
        // force use of Clreplaced.getClreplacedLoader()
        clreplacedLoader = null;
        proxyFactory.setProxyTargetClreplaced(true);
    }
    DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(ts);
    introduction.suppressInterface(TargetSource.clreplaced);
    proxyFactory.addAdvice(introduction);
    return proxyFactory.getProxy(clreplacedLoader);
}

18 View Source File : CommonAnnotationBeanPostProcessor.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Obtain a lazily resolving resource proxy for the given name and type,
 * delegating to {@link #getResource} on demand once a method call comes in.
 * @param element the descriptor for the annotated field/method
 * @param requestingBeanName the name of the requesting bean
 * @return the resource object (never {@code null})
 * @since 4.2
 * @see #getResource
 * @see Lazy
 */
protected Object buildLazyResourceProxy(final LookupElement element, final String requestingBeanName) {
    TargetSource ts = new TargetSource() {

        @Override
        public Clreplaced<?> getTargetClreplaced() {
            return element.lookupType;
        }

        @Override
        public boolean isStatic() {
            return false;
        }

        @Override
        public Object getTarget() {
            return getResource(element, requestingBeanName);
        }

        @Override
        public void releaseTarget(Object target) {
        }
    };
    ProxyFactory pf = new ProxyFactory();
    pf.setTargetSource(ts);
    if (element.lookupType.isInterface()) {
        pf.addInterface(element.lookupType);
    }
    ClreplacedLoader clreplacedLoader = (this.beanFactory instanceof ConfigurableBeanFactory ? ((ConfigurableBeanFactory) this.beanFactory).getBeanClreplacedLoader() : null);
    return pf.getProxy(clreplacedLoader);
}

18 View Source File : AbstractAutoProxyCreator.java
License : Apache License 2.0
Project Creator : langtianya

@Override
public Object postProcessBeforeInstantiation(Clreplaced<?> beanClreplaced, String beanName) throws BeansException {
    Object cacheKey = getCacheKey(beanClreplaced, beanName);
    if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        if (isInfrastructureClreplaced(beanClreplaced) || shouldSkip(beanClreplaced, beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return null;
        }
    }
    // Create proxy here if we have a custom TargetSource.
    // Suppresses unnecessary default instantiation of the target bean:
    // The TargetSource will handle target instances in a custom fashion.
    if (beanName != null) {
        TargetSource targetSource = getCustomTargetSource(beanClreplaced, beanName);
        if (targetSource != null) {
            this.targetSourcedBeans.add(beanName);
            Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClreplaced, beanName, targetSource);
            Object proxy = createProxy(beanClreplaced, beanName, specificInterceptors, targetSource);
            this.proxyTypes.put(cacheKey, proxy.getClreplaced());
            return proxy;
        }
    }
    return null;
}

18 View Source File : AbstractAutoProxyCreator.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Create an AOP proxy for the given bean.
 * @param beanClreplaced the clreplaced of the bean
 * @param beanName the name of the bean
 * @param specificInterceptors the set of interceptors that is
 * specific to this bean (may be empty, but not null)
 * @param targetSource the TargetSource for the proxy,
 * already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Clreplaced<?> beanClreplaced, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClreplaced((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClreplaced);
    }
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);
    if (!proxyFactory.isProxyTargetClreplaced()) {
        if (shouldProxyTargetClreplaced(beanClreplaced, beanName)) {
            proxyFactory.setProxyTargetClreplaced(true);
        } else {
            evaluateProxyInterfaces(beanClreplaced, proxyFactory);
        }
    }
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    for (Advisor advisor : advisors) {
        proxyFactory.addAdvisor(advisor);
    }
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    return proxyFactory.getProxy(getProxyClreplacedLoader());
}

18 View Source File : AopProxyUtils.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Determine the ultimate target clreplaced of the given bean instance, traversing
 * not only a top-level proxy but any number of nested proxies as well —
 * as long as possible without side effects, that is, just for singleton targets.
 * @param candidate the instance to check (might be an AOP proxy)
 * @return the ultimate target clreplaced (or the plain clreplaced of the given
 * object as fallback; never {@code null})
 * @see org.springframework.aop.TargetClreplacedAware#getTargetClreplaced()
 * @see Advised#getTargetSource()
 */
public static Clreplaced<?> ultimateTargetClreplaced(Object candidate) {
    replacedert.notNull(candidate, "Candidate object must not be null");
    Object current = candidate;
    Clreplaced<?> result = null;
    while (current instanceof TargetClreplacedAware) {
        result = ((TargetClreplacedAware) current).getTargetClreplaced();
        Object nested = null;
        if (current instanceof Advised) {
            TargetSource targetSource = ((Advised) current).getTargetSource();
            if (targetSource instanceof SingletonTargetSource) {
                nested = ((SingletonTargetSource) targetSource).getTarget();
            }
        }
        current = nested;
    }
    if (result == null) {
        result = (AopUtils.isCglibProxy(candidate) ? candidate.getClreplaced().getSuperclreplaced() : candidate.getClreplaced());
    }
    return result;
}

18 View Source File : SpringProxyUtils.java
License : Apache License 2.0
Project Creator : finleytianhe

/**
 * Find target clreplaced clreplaced.
 *
 * @param proxy the proxy
 * @return the clreplaced
 * @throws Exception the exception
 */
// 
public static Clreplaced<?> findTargetClreplaced(Object proxy) throws Exception {
    if (AopUtils.isAopProxy(proxy)) {
        AdvisedSupport advised = getAdvisedSupport(proxy);
        if (AopUtils.isJdkDynamicProxy(proxy)) {
            TargetSource targetSource = advised.getTargetSource();
            return targetSource instanceof EmptyTargetSource ? getFirstInterfaceByAdvised(advised) : targetSource.getTargetClreplaced();
        }
        Object target = advised.getTargetSource().getTarget();
        return findTargetClreplaced(target);
    } else {
        return proxy == null ? null : proxy.getClreplaced();
    }
}

18 View Source File : EagleTraceJdkProxy.java
License : Apache License 2.0
Project Creator : fang-yan-peng

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    TargetSource targetSource = this.advised.getTargetSource();
    Clreplaced<?> targetClreplaced = null;
    Object target = null;
    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        }
        if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        }
        if (method.getDeclaringClreplaced().isInterface() && method.getDeclaringClreplaced().isreplacedignableFrom(Advised.clreplaced)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }
        Object retVal;
        // May be null. Get as late as possible to minimize the time we "own" the target,
        // in case it comes from a pool.
        target = targetSource.getTarget();
        if (target != null) {
            targetClreplaced = target.getClreplaced();
        }
        if (EagleTraceMethodRecods.needTrace(method, targetClreplaced)) {
            boolean clear = Strings.isNullOrEmpty(TraceContext.getTraceId());
            try {
                if (clear) {
                    TraceContext.setTraceId(OpaqueGenerator.getDistributeOpaque());
                }
                retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
            } catch (Throwable e) {
                logger.error("Eagle trace error:  ", e);
                throw new EagleFrameException(e);
            } finally {
                if (clear) {
                    TraceContext.clear();
                }
            }
        } else {
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
        }
        // Mreplacedage return value if necessary.
        Clreplaced<?> returnType = method.getReturnType();
        if (retVal != null && retVal == target && returnType.isInstance(proxy) && !RawTargetAccess.clreplaced.isreplacedignableFrom(method.getDeclaringClreplaced())) {
            retVal = proxy;
        } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
            throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
        }
        return retVal;
    } finally {
        if (target != null && !targetSource.isStatic()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
    }
}

17 View Source File : ContextAnnotationAutowireCandidateResolver.java
License : MIT License
Project Creator : Vip-Augus

protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, @Nullable final String beanName) {
    replacedert.state(getBeanFactory() instanceof DefaultListableBeanFactory, "BeanFactory needs to be a DefaultListableBeanFactory");
    final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
    TargetSource ts = new TargetSource() {

        @Override
        public Clreplaced<?> getTargetClreplaced() {
            return descriptor.getDependencyType();
        }

        @Override
        public boolean isStatic() {
            return false;
        }

        @Override
        public Object getTarget() {
            Object target = beanFactory.doResolveDependency(descriptor, beanName, null, null);
            if (target == null) {
                Clreplaced<?> type = getTargetClreplaced();
                if (Map.clreplaced == type) {
                    return Collections.emptyMap();
                } else if (List.clreplaced == type) {
                    return Collections.emptyList();
                } else if (Set.clreplaced == type || Collection.clreplaced == type) {
                    return Collections.emptySet();
                }
                throw new NoSuchBeanDefinitionException(descriptor.getResolvableType(), "Optional dependency not present for lazy injection point");
            }
            return target;
        }

        @Override
        public void releaseTarget(Object target) {
        }
    };
    ProxyFactory pf = new ProxyFactory();
    pf.setTargetSource(ts);
    Clreplaced<?> dependencyType = descriptor.getDependencyType();
    if (dependencyType.isInterface()) {
        pf.addInterface(dependencyType);
    }
    return pf.getProxy(beanFactory.getBeanClreplacedLoader());
}

17 View Source File : JdkDynamicAopProxy.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Implementation of {@code InvocationHandler.invoke}.
 * <p>Callers will see exactly the exception thrown by the target,
 * unless a hook method throws an exception.
 */
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // 注释 8.12 jdk 动态代理重载的 invoke 方法
    MethodInvocation invocation;
    Object oldProxy = null;
    boolean setProxyContext = false;
    TargetSource targetSource = this.advised.targetSource;
    Object target = null;
    try {
        // 处理 equals 方法
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        } else if (method.getDeclaringClreplaced() == DecoratingProxy.clreplaced) {
            // There is only getDecoratedClreplaced() declared -> dispatch to proxy config.
            return AopProxyUtils.ultimateTargetClreplaced(this.advised);
        } else if (!this.advised.opaque && method.getDeclaringClreplaced().isInterface() && method.getDeclaringClreplaced().isreplacedignableFrom(Advised.clreplaced)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }
        Object retVal;
        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }
        // Get as late as possible to minimize the time we "own" the target,
        // in case it comes from a pool.
        target = targetSource.getTarget();
        Clreplaced<?> targetClreplaced = (target != null ? target.getClreplaced() : null);
        // Get the interception chain for this method.
        // 获取此方法的拦截链
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClreplaced);
        // Check whether we have any advice. If we don't, we can fallback on direct
        // reflective invocation of the target, and avoid creating a MethodInvocation.
        // 检查我们是否有任何切面逻辑。如果我们不这样做,我们可以回退直接反射调用目标,并避免创建 MethodInvocation。
        if (chain.isEmpty()) {
            // We can skip creating a MethodInvocation: just invoke the target directly
            // Note that the final invoker must be an InvokerInterceptor so we know it does
            // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        } else {
            // We need to create a method invocation...
            // 将拦截器封装在 ReflectiveMethodInvocation,便于使用 proceed 执行拦截器
            invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClreplaced, chain);
            // Proceed to the joinpoint through the interceptor chain.
            // 执行拦截器链
            retVal = invocation.proceed();
        }
        // Mreplacedage return value if necessary.
        Clreplaced<?> returnType = method.getReturnType();
        if (retVal != null && retVal == target && returnType != Object.clreplaced && returnType.isInstance(proxy) && !RawTargetAccess.clreplaced.isreplacedignableFrom(method.getDeclaringClreplaced())) {
            // Special case: it returned "this" and the return type of the method
            // is type-compatible. Note that we can't help if the target sets
            // a reference to itself in another returned object.
            retVal = proxy;
        } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
            throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
        }
        return retVal;
    } finally {
        if (target != null && !targetSource.isStatic()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}

17 View Source File : AdvisedSupport.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Base clreplaced for AOP proxy configuration managers.
 * These are not themselves AOP proxies, but subclreplacedes of this clreplaced are
 * normally factories from which AOP proxy instances are obtained directly.
 *
 * <p>This clreplaced frees subclreplacedes of the housekeeping of Advices
 * and Advisors, but doesn't actually implement proxy creation
 * methods, which are provided by subclreplacedes.
 *
 * <p>This clreplaced is serializable; subclreplacedes need not be.
 * This clreplaced is used to hold snapshots of proxies.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see org.springframework.aop.framework.AopProxy
 */
public clreplaced AdvisedSupport extends ProxyConfig implements Advised {

    /**
     * use serialVersionUID from Spring 2.0 for interoperability.
     */
    private static final long serialVersionUID = 2651364800145442165L;

    /**
     * Canonical TargetSource when there's no target, and behavior is
     * supplied by the advisors.
     */
    public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE;

    /**
     * Package-protected to allow direct access for efficiency.
     */
    TargetSource targetSource = EMPTY_TARGET_SOURCE;

    /**
     * Whether the Advisors are already filtered for the specific target clreplaced.
     */
    private boolean preFiltered = false;

    /**
     * The AdvisorChainFactory to use.
     */
    AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();

    /**
     * Cache with Method as key and advisor chain List as value.
     */
    private transient Map<MethodCacheKey, List<Object>> methodCache;

    /**
     * Interfaces to be implemented by the proxy. Held in List to keep the order
     * of registration, to create JDK proxy with specified order of interfaces.
     */
    private List<Clreplaced<?>> interfaces = new ArrayList<>();

    /**
     * List of Advisors. If an Advice is added, it will be wrapped
     * in an Advisor before being added to this List.
     */
    private List<Advisor> advisors = new ArrayList<>();

    /**
     * Array updated on changes to the advisors list, which is easier
     * to manipulate internally.
     */
    private Advisor[] advisorArray = new Advisor[0];

    /**
     * No-arg constructor for use as a JavaBean.
     */
    public AdvisedSupport() {
        this.methodCache = new ConcurrentHashMap<>(32);
    }

    /**
     * Create a AdvisedSupport instance with the given parameters.
     * @param interfaces the proxied interfaces
     */
    public AdvisedSupport(Clreplaced<?>... interfaces) {
        this();
        setInterfaces(interfaces);
    }

    /**
     * Set the given object as target.
     * Will create a SingletonTargetSource for the object.
     * @see #setTargetSource
     * @see org.springframework.aop.target.SingletonTargetSource
     */
    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;
    }

    /**
     * Set a target clreplaced to be proxied, indicating that the proxy
     * should be castable to the given clreplaced.
     * <p>Internally, an {@link org.springframework.aop.target.EmptyTargetSource}
     * for the given target clreplaced will be used. The kind of proxy needed
     * will be determined on actual creation of the proxy.
     * <p>This is a replacement for setting a "targetSource" or "target",
     * for the case where we want a proxy based on a target clreplaced
     * (which can be an interface or a concrete clreplaced) without having
     * a fully capable TargetSource available.
     * @see #setTargetSource
     * @see #setTarget
     */
    public void setTargetClreplaced(@Nullable Clreplaced<?> targetClreplaced) {
        this.targetSource = EmptyTargetSource.forClreplaced(targetClreplaced);
    }

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

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

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

    /**
     * Set the advisor chain factory to use.
     * <p>Default is a {@link DefaultAdvisorChainFactory}.
     */
    public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) {
        replacedert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null");
        this.advisorChainFactory = advisorChainFactory;
    }

    /**
     * Return the advisor chain factory to use (never {@code null}).
     */
    public AdvisorChainFactory getAdvisorChainFactory() {
        return this.advisorChainFactory;
    }

    /**
     * Set the interfaces to be proxied.
     */
    public void setInterfaces(Clreplaced<?>... interfaces) {
        replacedert.notNull(interfaces, "Interfaces must not be null");
        this.interfaces.clear();
        for (Clreplaced<?> ifc : interfaces) {
            addInterface(ifc);
        }
    }

    /**
     * Add a new proxied interface.
     * @param intf the additional interface to proxy
     */
    public void addInterface(Clreplaced<?> intf) {
        replacedert.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();
        }
    }

    /**
     * Remove a proxied interface.
     * <p>Does nothing if the given interface isn't proxied.
     * @param intf the interface to remove from the proxy
     * @return {@code true} if the interface was removed; {@code false}
     * if the interface was not found and hence could not be removed
     */
    public boolean removeInterface(Clreplaced<?> intf) {
        return this.interfaces.remove(intf);
    }

    @Override
    public Clreplaced<?>[] getProxiedInterfaces() {
        return ClreplacedUtils.toClreplacedArray(this.interfaces);
    }

    @Override
    public boolean isInterfaceProxied(Clreplaced<?> intf) {
        for (Clreplaced<?> proxyIntf : this.interfaces) {
            if (intf.isreplacedignableFrom(proxyIntf)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public final Advisor[] getAdvisors() {
        return this.advisorArray;
    }

    @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) {
            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.get(index);
        if (advisor instanceof IntroductionAdvisor) {
            IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
            // We need to remove introduction interfaces.
            for (int j = 0; j < ia.getInterfaces().length; j++) {
                removeInterface(ia.getInterfaces()[j]);
            }
        }
        this.advisors.remove(index);
        updateAdvisorArray();
        adviceChanged();
    }

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

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

    /**
     * Add all of the given advisors to this proxy configuration.
     * @param advisors the advisors to register
     */
    public void addAdvisors(Advisor... advisors) {
        addAdvisors(Arrays.asList(advisors));
    }

    /**
     * Add all of the given advisors to this proxy configuration.
     * @param advisors the advisors to register
     */
    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);
                }
                replacedert.notNull(advisor, "Advisor must not be null");
                this.advisors.add(advisor);
            }
            updateAdvisorArray();
            adviceChanged();
        }
    }

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

    private void addAdvisorInternal(int pos, Advisor advisor) throws AopConfigException {
        replacedert.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);
        updateAdvisorArray();
        adviceChanged();
    }

    /**
     * Bring the array up to date with the list.
     */
    protected final void updateAdvisorArray() {
        this.advisorArray = this.advisors.toArray(new Advisor[0]);
    }

    /**
     * Allows uncontrolled access to the {@link List} of {@link Advisor Advisors}.
     * <p>Use with care, and remember to {@link #updateAdvisorArray() refresh the advisor array}
     * and {@link #adviceChanged() fire advice changed events} when making any modifications.
     */
    protected final List<Advisor> getAdvisorsInternal() {
        return this.advisors;
    }

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

    /**
     * Cannot add introductions this way unless the advice implements IntroductionInfo.
     */
    @Override
    public void addAdvice(int pos, Advice advice) throws AopConfigException {
        replacedert.notNull(advice, "Advice must not be null");
        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) {
        replacedert.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;
    }

    /**
     * Is the given advice included in any advisor within this proxy configuration?
     * @param advice the advice to check inclusion of
     * @return whether this advice instance is included
     */
    public boolean adviceIncluded(@Nullable Advice advice) {
        if (advice != null) {
            for (Advisor advisor : this.advisors) {
                if (advisor.getAdvice() == advice) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Count advices of the given clreplaced.
     * @param adviceClreplaced the advice clreplaced to check
     * @return the count of the interceptors of this clreplaced or subclreplacedes
     */
    public int countAdvicesOfType(@Nullable Clreplaced<?> adviceClreplaced) {
        int count = 0;
        if (adviceClreplaced != null) {
            for (Advisor advisor : this.advisors) {
                if (adviceClreplaced.isInstance(advisor.getAdvice())) {
                    count++;
                }
            }
        }
        return count;
    }

    /**
     * Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects
     * for the given method, based on this configuration.
     * @param method the proxied method
     * @param targetClreplaced the target clreplaced
     * @return a List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
     */
    public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Clreplaced<?> targetClreplaced) {
        MethodCacheKey cacheKey = new MethodCacheKey(method);
        List<Object> cached = this.methodCache.get(cacheKey);
        if (cached == null) {
            cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(this, method, targetClreplaced);
            this.methodCache.put(cacheKey, cached);
        }
        return cached;
    }

    /**
     * Invoked when advice has changed.
     */
    protected void adviceChanged() {
        this.methodCache.clear();
    }

    /**
     * Call this method on a new instance created by the no-arg constructor
     * to create an independent copy of the configuration from the given object.
     * @param other the AdvisedSupport object to copy configuration from
     */
    protected void copyConfigurationFrom(AdvisedSupport other) {
        copyConfigurationFrom(other, other.targetSource, new ArrayList<>(other.advisors));
    }

    /**
     * Copy the AOP configuration from the given AdvisedSupport object,
     * but allow subsreplacedution of a fresh TargetSource and a given interceptor chain.
     * @param other the AdvisedSupport object to take proxy configuration from
     * @param targetSource the new TargetSource
     * @param advisors the Advisors for the chain
     */
    protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List<Advisor> advisors) {
        copyFrom(other);
        this.targetSource = targetSource;
        this.advisorChainFactory = other.advisorChainFactory;
        this.interfaces = new ArrayList<>(other.interfaces);
        for (Advisor advisor : advisors) {
            if (advisor instanceof IntroductionAdvisor) {
                validateIntroductionAdvisor((IntroductionAdvisor) advisor);
            }
            replacedert.notNull(advisor, "Advisor must not be null");
            this.advisors.add(advisor);
        }
        updateAdvisorArray();
        adviceChanged();
    }

    /**
     * Build a configuration-only copy of this AdvisedSupport,
     * replacing the TargetSource.
     */
    AdvisedSupport getConfigurationOnlyCopy() {
        AdvisedSupport copy = new AdvisedSupport();
        copy.copyFrom(this);
        copy.targetSource = EmptyTargetSource.forClreplaced(getTargetClreplaced(), getTargetSource().isStatic());
        copy.advisorChainFactory = this.advisorChainFactory;
        copy.interfaces = this.interfaces;
        copy.advisors = this.advisors;
        copy.updateAdvisorArray();
        return copy;
    }

    // ---------------------------------------------------------------------
    // Serialization support
    // ---------------------------------------------------------------------
    private void readObject(ObjectInputStream ois) throws IOException, ClreplacedNotFoundException {
        // Rely on default serialization; just initialize state after deserialization.
        ois.defaultReadObject();
        // Initialize transient fields.
        this.methodCache = new ConcurrentHashMap<>(32);
    }

    @Override
    public String toProxyConfigString() {
        return toString();
    }

    /**
     * For debugging/diagnostic use.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(getClreplaced().getName());
        sb.append(": ").append(this.interfaces.size()).append(" interfaces ");
        sb.append(ClreplacedUtils.clreplacedNamesToString(this.interfaces)).append("; ");
        sb.append(this.advisors.size()).append(" advisors ");
        sb.append(this.advisors).append("; ");
        sb.append("targetSource [").append(this.targetSource).append("]; ");
        sb.append(super.toString());
        return sb.toString();
    }

    /**
     * Simple wrapper clreplaced around a Method. Used as the key when
     * caching methods, for efficient equals and hashCode comparisons.
     */
    private static final clreplaced 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 boolean equals(Object other) {
            return (this == other || (other instanceof MethodCacheKey && this.method == ((MethodCacheKey) other).method));
        }

        @Override
        public int hashCode() {
            return this.hashCode;
        }

        @Override
        public String toString() {
            return this.method.toString();
        }

        @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;
        }
    }
}

17 View Source File : AbstractSingletonProxyFactoryBean.java
License : MIT License
Project Creator : Vip-Augus

@Override
public void afterPropertiesSet() {
    if (this.target == null) {
        throw new IllegalArgumentException("Property 'target' is required");
    }
    if (this.target instanceof String) {
        throw new IllegalArgumentException("'target' needs to be a bean reference, not a bean name as value");
    }
    if (this.proxyClreplacedLoader == null) {
        this.proxyClreplacedLoader = ClreplacedUtils.getDefaultClreplacedLoader();
    }
    ProxyFactory proxyFactory = new ProxyFactory();
    if (this.preInterceptors != null) {
        for (Object interceptor : this.preInterceptors) {
            proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
        }
    }
    // Add the main interceptor (typically an Advisor).
    proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(createMainInterceptor()));
    if (this.postInterceptors != null) {
        for (Object interceptor : this.postInterceptors) {
            proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
        }
    }
    proxyFactory.copyFrom(this);
    TargetSource targetSource = createTargetSource(this.target);
    proxyFactory.setTargetSource(targetSource);
    if (this.proxyInterfaces != null) {
        proxyFactory.setInterfaces(this.proxyInterfaces);
    } else if (!isProxyTargetClreplaced()) {
        // Rely on AOP infrastructure to tell us what interfaces to proxy.
        Clreplaced<?> targetClreplaced = targetSource.getTargetClreplaced();
        if (targetClreplaced != null) {
            proxyFactory.setInterfaces(ClreplacedUtils.getAllInterfacesForClreplaced(targetClreplaced, this.proxyClreplacedLoader));
        }
    }
    postProcessProxyFactory(proxyFactory);
    this.proxy = proxyFactory.getProxy(this.proxyClreplacedLoader);
}

17 View Source File : ContextAnnotationAutowireCandidateResolver.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * 创建延迟代理类
 */
protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, @Nullable final String beanName) {
    replacedert.state(getBeanFactory() instanceof DefaultListableBeanFactory, "BeanFactory needs to be a DefaultListableBeanFactory");
    final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
    // target source 接口 目标对象
    TargetSource ts = new TargetSource() {

        @Override
        public Clreplaced<?> getTargetClreplaced() {
            return descriptor.getDependencyType();
        }

        @Override
        public boolean isStatic() {
            return false;
        }

        @Override
        public Object getTarget() {
            // DefaultListableBeanFactory 中 doResolveDependency 调用
            Object target = beanFactory.doResolveDependency(descriptor, beanName, null, null);
            // 为空的情况下根据类型返回空对象
            if (target == null) {
                Clreplaced<?> type = getTargetClreplaced();
                if (Map.clreplaced == type) {
                    return Collections.emptyMap();
                } else if (List.clreplaced == type) {
                    return Collections.emptyList();
                } else if (Set.clreplaced == type || Collection.clreplaced == type) {
                    return Collections.emptySet();
                }
                throw new NoSuchBeanDefinitionException(descriptor.getResolvableType(), "Optional dependency not present for lazy injection point");
            }
            return target;
        }

        @Override
        public void releaseTarget(Object target) {
        }
    };
    // 代理工厂
    ProxyFactory pf = new ProxyFactory();
    // 设置数据信息
    pf.setTargetSource(ts);
    Clreplaced<?> dependencyType = descriptor.getDependencyType();
    if (dependencyType.isInterface()) {
        pf.addInterface(dependencyType);
    }
    // 代理工厂创建对象
    return pf.getProxy(beanFactory.getBeanClreplacedLoader());
}

17 View Source File : JdkDynamicAopProxy.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Implementation of {@code InvocationHandler.invoke}.
 * <p>Callers will see exactly the exception thrown by the target,
 * unless a hook method throws an exception.
 */
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object oldProxy = null;
    boolean setProxyContext = false;
    TargetSource targetSource = this.advised.targetSource;
    Object target = null;
    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        } else if (method.getDeclaringClreplaced() == DecoratingProxy.clreplaced) {
            // There is only getDecoratedClreplaced() declared -> dispatch to proxy config.
            return AopProxyUtils.ultimateTargetClreplaced(this.advised);
        } else if (!this.advised.opaque && method.getDeclaringClreplaced().isInterface() && method.getDeclaringClreplaced().isreplacedignableFrom(Advised.clreplaced)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }
        Object retVal;
        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }
        // Get as late as possible to minimize the time we "own" the target,
        // in case it comes from a pool.
        target = targetSource.getTarget();
        Clreplaced<?> targetClreplaced = (target != null ? target.getClreplaced() : null);
        // Get the interception chain for this method.
        // 获取拦截器
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClreplaced);
        // Check whether we have any advice. If we don't, we can fallback on direct
        // reflective invocation of the target, and avoid creating a MethodInvocation.
        // 是否存在拦截器
        if (chain.isEmpty()) {
            // We can skip creating a MethodInvocation: just invoke the target directly
            // Note that the final invoker must be an InvokerInterceptor so we know it does
            // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
            // 参数列表
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            // 调用切点方法
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        } else {
            // We need to create a method invocation...
            // 拦截器组装
            MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClreplaced, chain);
            // Proceed to the joinpoint through the interceptor chain.
            // 执行拦截器的链路
            retVal = invocation.proceed();
        }
        // Mreplacedage return value if necessary.
        // 返回值类型获取
        Clreplaced<?> returnType = method.getReturnType();
        // 返回结果判断
        if (retVal != null && retVal == target && returnType != Object.clreplaced && returnType.isInstance(proxy) && !RawTargetAccess.clreplaced.isreplacedignableFrom(method.getDeclaringClreplaced())) {
            // Special case: it returned "this" and the return type of the method
            // is type-compatible. Note that we can't help if the target sets
            // a reference to itself in another returned object.
            retVal = proxy;
        } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
            throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
        }
        return retVal;
    } finally {
        if (target != null && !targetSource.isStatic()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}

17 View Source File : AdvisedSupport.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Base clreplaced for AOP proxy configuration managers. These are not themselves AOP proxies, but
 * subclreplacedes of this clreplaced are normally factories from which AOP proxy instances are obtained
 * directly.
 *
 * <p>This clreplaced frees subclreplacedes of the housekeeping of Advices
 * and Advisors, but doesn't actually implement proxy creation methods, which are provided by
 * subclreplacedes.
 *
 * <p>This clreplaced is serializable; subclreplacedes need not be.
 * This clreplaced is used to hold snapshots of proxies.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see org.springframework.aop.framework.AopProxy
 */
public clreplaced 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;

    /**
     * use serialVersionUID from Spring 2.0 for interoperability.
     */
    private static final long serialVersionUID = 2651364800145442165L;

    /**
     * Package-protected to allow direct access for efficiency.
     */
    TargetSource targetSource = EMPTY_TARGET_SOURCE;

    /**
     * The AdvisorChainFactory to use.
     */
    AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();

    /**
     * Whether the Advisors are already filtered for the specific target clreplaced.
     */
    private boolean preFiltered = false;

    /**
     * Cache with Method as key and advisor chain List as value.
     */
    private transient Map<MethodCacheKey, List<Object>> methodCache;

    /**
     * Interfaces to be implemented by the proxy. Held in List to keep the order of registration, to
     * create JDK proxy with specified order of interfaces.
     * <p>
     * 接口列表
     */
    private List<Clreplaced<?>> interfaces = new ArrayList<>();

    /**
     * List of Advisors. If an Advice is added, it will be wrapped in an Advisor before being added
     * to this List.
     */
    private List<Advisor> advisors = new ArrayList<>();

    /**
     * Array updated on changes to the advisors list, which is easier to manipulate internally.
     */
    private Advisor[] advisorArray = new Advisor[0];

    /**
     * No-arg constructor for use as a JavaBean.
     */
    public AdvisedSupport() {
        this.methodCache = new ConcurrentHashMap<>(32);
    }

    /**
     * Create a AdvisedSupport instance with the given parameters.
     *
     * @param interfaces the proxied interfaces
     */
    public AdvisedSupport(Clreplaced<?>... interfaces) {
        this();
        setInterfaces(interfaces);
    }

    /**
     * Set the given object as target. Will create a SingletonTargetSource for the object.
     *
     * @see #setTargetSource
     * @see org.springframework.aop.target.SingletonTargetSource
     */
    public void setTarget(Object target) {
        setTargetSource(new SingletonTargetSource(target));
    }

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

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

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

    /**
     * Set a target clreplaced to be proxied, indicating that the proxy should be castable to the given
     * clreplaced.
     * <p>Internally, an {@link org.springframework.aop.target.EmptyTargetSource}
     * for the given target clreplaced will be used. The kind of proxy needed will be determined on
     * actual creation of the proxy.
     * <p>This is a replacement for setting a "targetSource" or "target",
     * for the case where we want a proxy based on a target clreplaced (which can be an interface or a
     * concrete clreplaced) without having a fully capable TargetSource available.
     *
     * @see #setTargetSource
     * @see #setTarget
     */
    public void setTargetClreplaced(@Nullable Clreplaced<?> targetClreplaced) {
        this.targetSource = EmptyTargetSource.forClreplaced(targetClreplaced);
    }

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

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

    /**
     * Return the advisor chain factory to use (never {@code null}).
     */
    public AdvisorChainFactory getAdvisorChainFactory() {
        return this.advisorChainFactory;
    }

    /**
     * Set the advisor chain factory to use.
     * <p>Default is a {@link DefaultAdvisorChainFactory}.
     */
    public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) {
        replacedert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null");
        this.advisorChainFactory = advisorChainFactory;
    }

    /**
     * Set the interfaces to be proxied.
     */
    public void setInterfaces(Clreplaced<?>... interfaces) {
        replacedert.notNull(interfaces, "Interfaces must not be null");
        this.interfaces.clear();
        for (Clreplaced<?> ifc : interfaces) {
            addInterface(ifc);
        }
    }

    /**
     * Add a new proxied interface.
     * <p>
     * 添加代理接口
     *
     * @param intf the additional interface to proxy
     */
    public void addInterface(Clreplaced<?> intf) {
        replacedert.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();
        }
    }

    /**
     * Remove a proxied interface.
     * <p>Does nothing if the given interface isn't proxied.
     *
     * @param intf the interface to remove from the proxy
     *
     * @return {@code true} if the interface was removed; {@code false} if the interface was not
     * found and hence could not be removed
     */
    public boolean removeInterface(Clreplaced<?> intf) {
        return this.interfaces.remove(intf);
    }

    @Override
    public Clreplaced<?>[] getProxiedInterfaces() {
        return ClreplacedUtils.toClreplacedArray(this.interfaces);
    }

    @Override
    public boolean isInterfaceProxied(Clreplaced<?> intf) {
        for (Clreplaced<?> proxyIntf : this.interfaces) {
            if (intf.isreplacedignableFrom(proxyIntf)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public final Advisor[] getAdvisors() {
        return this.advisorArray;
    }

    @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) {
            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;
            // We need to remove introduction interfaces.
            for (Clreplaced<?> ifc : ia.getInterfaces()) {
                removeInterface(ifc);
            }
        }
        updateAdvisorArray();
        adviceChanged();
    }

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

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

    /**
     * Add all of the given advisors to this proxy configuration.
     *
     * @param advisors the advisors to register
     */
    public void addAdvisors(Advisor... advisors) {
        addAdvisors(Arrays.asList(advisors));
    }

    /**
     * Add all of the given advisors to this proxy configuration.
     *
     * @param advisors the advisors to register
     */
    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);
                }
                replacedert.notNull(advisor, "Advisor must not be null");
                this.advisors.add(advisor);
            }
            updateAdvisorArray();
            adviceChanged();
        }
    }

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

    private void addAdvisorInternal(int pos, Advisor advisor) throws AopConfigException {
        replacedert.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);
        updateAdvisorArray();
        adviceChanged();
    }

    /**
     * Bring the array up to date with the list.
     */
    protected final void updateAdvisorArray() {
        this.advisorArray = this.advisors.toArray(new Advisor[0]);
    }

    /**
     * Allows uncontrolled access to the {@link List} of {@link Advisor Advisors}.
     * <p>Use with care, and remember to {@link #updateAdvisorArray() refresh the advisor array}
     * and {@link #adviceChanged() fire advice changed events} when making any modifications.
     */
    protected final List<Advisor> getAdvisorsInternal() {
        return this.advisors;
    }

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

    /**
     * Cannot add introductions this way unless the advice implements IntroductionInfo.
     */
    @Override
    public void addAdvice(int pos, Advice advice) throws AopConfigException {
        replacedert.notNull(advice, "Advice must not be null");
        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) {
        replacedert.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;
    }

    /**
     * Is the given advice included in any advisor within this proxy configuration?
     *
     * @param advice the advice to check inclusion of
     *
     * @return whether this advice instance is included
     */
    public boolean adviceIncluded(@Nullable Advice advice) {
        if (advice != null) {
            for (Advisor advisor : this.advisors) {
                if (advisor.getAdvice() == advice) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Count advices of the given clreplaced.
     *
     * @param adviceClreplaced the advice clreplaced to check
     *
     * @return the count of the interceptors of this clreplaced or subclreplacedes
     */
    public int countAdvicesOfType(@Nullable Clreplaced<?> adviceClreplaced) {
        int count = 0;
        if (adviceClreplaced != null) {
            for (Advisor advisor : this.advisors) {
                if (adviceClreplaced.isInstance(advisor.getAdvice())) {
                    count++;
                }
            }
        }
        return count;
    }

    /**
     * Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects for the given
     * method, based on this configuration.
     *
     * @param method      the proxied method
     * @param targetClreplaced the target clreplaced
     *
     * @return a List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
     */
    public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Clreplaced<?> targetClreplaced) {
        MethodCacheKey cacheKey = new MethodCacheKey(method);
        List<Object> cached = this.methodCache.get(cacheKey);
        if (cached == null) {
            cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(this, method, targetClreplaced);
            this.methodCache.put(cacheKey, cached);
        }
        return cached;
    }

    /**
     * Invoked when advice has changed.
     */
    protected void adviceChanged() {
        this.methodCache.clear();
    }

    /**
     * Call this method on a new instance created by the no-arg constructor to create an independent
     * copy of the configuration from the given object.
     *
     * @param other the AdvisedSupport object to copy configuration from
     */
    protected void copyConfigurationFrom(AdvisedSupport other) {
        copyConfigurationFrom(other, other.targetSource, new ArrayList<>(other.advisors));
    }

    /**
     * Copy the AOP configuration from the given AdvisedSupport object, but allow subsreplacedution of a
     * fresh TargetSource and a given interceptor chain.
     *
     * @param other        the AdvisedSupport object to take proxy configuration from
     * @param targetSource the new TargetSource
     * @param advisors     the Advisors for the chain
     */
    protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List<Advisor> advisors) {
        copyFrom(other);
        this.targetSource = targetSource;
        this.advisorChainFactory = other.advisorChainFactory;
        this.interfaces = new ArrayList<>(other.interfaces);
        for (Advisor advisor : advisors) {
            if (advisor instanceof IntroductionAdvisor) {
                validateIntroductionAdvisor((IntroductionAdvisor) advisor);
            }
            replacedert.notNull(advisor, "Advisor must not be null");
            this.advisors.add(advisor);
        }
        updateAdvisorArray();
        adviceChanged();
    }

    /**
     * Build a configuration-only copy of this AdvisedSupport, replacing the TargetSource.
     */
    AdvisedSupport getConfigurationOnlyCopy() {
        AdvisedSupport copy = new AdvisedSupport();
        copy.copyFrom(this);
        copy.targetSource = EmptyTargetSource.forClreplaced(getTargetClreplaced(), getTargetSource().isStatic());
        copy.advisorChainFactory = this.advisorChainFactory;
        copy.interfaces = this.interfaces;
        copy.advisors = this.advisors;
        copy.updateAdvisorArray();
        return copy;
    }

    // ---------------------------------------------------------------------
    // Serialization support
    // ---------------------------------------------------------------------
    private void readObject(ObjectInputStream ois) throws IOException, ClreplacedNotFoundException {
        // Rely on default serialization; just initialize state after deserialization.
        ois.defaultReadObject();
        // Initialize transient fields.
        this.methodCache = new ConcurrentHashMap<>(32);
    }

    @Override
    public String toProxyConfigString() {
        return toString();
    }

    /**
     * For debugging/diagnostic use.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(getClreplaced().getName());
        sb.append(": ").append(this.interfaces.size()).append(" interfaces ");
        sb.append(ClreplacedUtils.clreplacedNamesToString(this.interfaces)).append("; ");
        sb.append(this.advisors.size()).append(" advisors ");
        sb.append(this.advisors).append("; ");
        sb.append("targetSource [").append(this.targetSource).append("]; ");
        sb.append(super.toString());
        return sb.toString();
    }

    /**
     * Simple wrapper clreplaced around a Method. Used as the key when caching methods, for efficient
     * equals and hashCode comparisons.
     */
    private static final clreplaced 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 boolean equals(@Nullable Object other) {
            return (this == other || (other instanceof MethodCacheKey && this.method == ((MethodCacheKey) other).method));
        }

        @Override
        public int hashCode() {
            return this.hashCode;
        }

        @Override
        public String toString() {
            return this.method.toString();
        }

        @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;
        }
    }
}

17 View Source File : SeataAutoDataSourceProxyCreator.java
License : Apache License 2.0
Project Creator : seata

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Clreplaced<?> beanClreplaced, String beanName, TargetSource customTargetSource) throws BeansException {
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Auto proxy of [{}]", beanName);
    }
    return new Object[] { advisor };
}

See More Examples