org.springframework.core.DecoratingProxy#org.springframework.aop.TargetSource源码实例Demo

下面列出了org.springframework.core.DecoratingProxy#org.springframework.aop.TargetSource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lams   文件: AdvisedSupport.java
/**
 * Copy the AOP configuration from the given AdvisedSupport object,
 * but allow substitution 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<Class<?>>(other.interfaces);
	for (Advisor advisor : advisors) {
		if (advisor instanceof IntroductionAdvisor) {
			validateIntroductionAdvisor((IntroductionAdvisor) advisor);
		}
		Assert.notNull(advisor, "Advisor must not be null");
		this.advisors.add(advisor);
	}
	updateAdvisorArray();
	adviceChanged();
}
 
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String name, TargetSource customTargetSource) {
	if (StaticMessageSource.class.equals(beanClass)) {
		return DO_NOT_PROXY;
	}
	else if (name.endsWith("ToBeProxied")) {
		boolean isFactoryBean = FactoryBean.class.isAssignableFrom(beanClass);
		if ((this.proxyFactoryBean && isFactoryBean) || (this.proxyObject && !isFactoryBean)) {
			return new Object[] {this.testInterceptor};
		}
		else {
			return DO_NOT_PROXY;
		}
	}
	else {
		return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
	}
}
 
源代码3 项目: spring-analysis-note   文件: ProxyFactoryBean.java
/**
 * Return a TargetSource to use when creating a proxy. If the target was not
 * specified at the end of the interceptorNames list, the TargetSource will be
 * this class's TargetSource member. Otherwise, we get the target bean and wrap
 * it in a TargetSource if necessary.
 */
private TargetSource freshTargetSource() {
	if (this.targetName == null) {
		if (logger.isTraceEnabled()) {
			logger.trace("Not refreshing target: Bean name not specified in 'interceptorNames'.");
		}
		return this.targetSource;
	}
	else {
		if (this.beanFactory == null) {
			throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
					"- cannot resolve target with name '" + this.targetName + "'");
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Refreshing target with name '" + this.targetName + "'");
		}
		Object target = this.beanFactory.getBean(this.targetName);
		return (target instanceof TargetSource ? (TargetSource) target : new SingletonTargetSource(target));
	}
}
 
源代码4 项目: spring-analysis-note   文件: AdvisedSupport.java
/**
 * Copy the AOP configuration from the given AdvisedSupport object,
 * but allow substitution 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);
		}
		Assert.notNull(advisor, "Advisor must not be null");
		this.advisors.add(advisor);
	}
	updateAdvisorArray();
	adviceChanged();
}
 
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String name, @Nullable TargetSource customTargetSource) {
	if (StaticMessageSource.class.equals(beanClass)) {
		return DO_NOT_PROXY;
	}
	else if (name.endsWith("ToBeProxied")) {
		boolean isFactoryBean = FactoryBean.class.isAssignableFrom(beanClass);
		if ((this.proxyFactoryBean && isFactoryBean) || (this.proxyObject && !isFactoryBean)) {
			return new Object[] {this.testInterceptor};
		}
		else {
			return DO_NOT_PROXY;
		}
	}
	else {
		return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
	}
}
 
源代码6 项目: spring4-understanding   文件: AopProxyUtils.java
/**
 * Determine the ultimate target class of the given bean instance, traversing
 * not only a top-level proxy but any number of nested proxies as well &mdash;
 * 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 class (or the plain class of the given
 * object as fallback; never {@code null})
 * @see org.springframework.aop.TargetClassAware#getTargetClass()
 * @see Advised#getTargetSource()
 */
public static Class<?> ultimateTargetClass(Object candidate) {
	Assert.notNull(candidate, "Candidate object must not be null");
	Object current = candidate;
	Class<?> result = null;
	while (current instanceof TargetClassAware) {
		result = ((TargetClassAware) current).getTargetClass();
		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.getClass().getSuperclass() : candidate.getClass());
	}
	return result;
}
 
/**
 * 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.
 * Subclasses can override this method to use a different mechanism.
 * @param beanClass the class 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(Class<?> beanClass, 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(beanClass, 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;
}
 
源代码8 项目: lams   文件: AbstractSingletonProxyFactoryBean.java
@Override
public Class<?> getObjectType() {
	if (this.proxy != null) {
		return this.proxy.getClass();
	}
	if (this.proxyInterfaces != null && this.proxyInterfaces.length == 1) {
		return this.proxyInterfaces[0];
	}
	if (this.target instanceof TargetSource) {
		return ((TargetSource) this.target).getTargetClass();
	}
	if (this.target != null) {
		return this.target.getClass();
	}
	return null;
}
 
/**
 * 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.
 * Subclasses can override this method to use a different mechanism.
 * @param beanClass the class 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(Class<?> beanClass, 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(beanClass, 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;
}
 
@Override
@Nullable
public Class<?> getObjectType() {
	if (this.proxy != null) {
		return this.proxy.getClass();
	}
	if (this.proxyInterfaces != null && this.proxyInterfaces.length == 1) {
		return this.proxyInterfaces[0];
	}
	if (this.target instanceof TargetSource) {
		return ((TargetSource) this.target).getTargetClass();
	}
	if (this.target != null) {
		return this.target.getClass();
	}
	return null;
}
 
源代码11 项目: phone   文件: AopProxyUtils.java
/**
 * 是否代理了多次
 * 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);
    }
}
 
源代码12 项目: lams   文件: ProxyFactoryBean.java
/**
 * Return a TargetSource to use when creating a proxy. If the target was not
 * specified at the end of the interceptorNames list, the TargetSource will be
 * this class's TargetSource member. Otherwise, we get the target bean and wrap
 * it in a TargetSource if necessary.
 */
private TargetSource freshTargetSource() {
	if (this.targetName == null) {
		if (logger.isTraceEnabled()) {
			logger.trace("Not refreshing target: Bean name not specified in 'interceptorNames'.");
		}
		return this.targetSource;
	}
	else {
		if (this.beanFactory == null) {
			throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
					"- cannot resolve target with name '" + this.targetName + "'");
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Refreshing target with name '" + this.targetName + "'");
		}
		Object target = this.beanFactory.getBean(this.targetName);
		return (target instanceof TargetSource ? (TargetSource) target : new SingletonTargetSource(target));
	}
}
 
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String name, @Nullable TargetSource customTargetSource) {
	if (StaticMessageSource.class.equals(beanClass)) {
		return DO_NOT_PROXY;
	}
	else if (name.endsWith("ToBeProxied")) {
		boolean isFactoryBean = FactoryBean.class.isAssignableFrom(beanClass);
		if ((this.proxyFactoryBean && isFactoryBean) || (this.proxyObject && !isFactoryBean)) {
			return new Object[] {this.testInterceptor};
		}
		else {
			return DO_NOT_PROXY;
		}
	}
	else {
		return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
	}
}
 
源代码14 项目: eclair   文件: EclairProxyCreator.java
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource customTargetSource) throws BeansException {
    Class<?> targetClass = beanClassCache.computeIfAbsent(beanName, s -> ClassUtils.getUserClass(beanClass));
    Object[] cachedAdvisors = advisorsCache.get(targetClass);
    if (nonNull(cachedAdvisors)) {
        return cachedAdvisors.length == 0 ? AbstractAutoProxyCreator.DO_NOT_PROXY : cachedAdvisors;
    }
    if (!supports(targetClass)) {
        advisorsCache.put(targetClass, EMPTY_ARRAY);
        return AbstractAutoProxyCreator.DO_NOT_PROXY;
    }
    if (validate) {
        annotationExtractor.getCandidateMethods(targetClass).forEach(methodValidator::validate);
    }
    MdcAdvisor mdcAdvisor = getMdcAdvisor(targetClass);
    List<LogAdvisor> logAdvisors = getLoggingAdvisors(targetClass);
    Object[] composedAdvisors = composeAdvisors(mdcAdvisor, logAdvisors);
    advisorsCache.put(targetClass, composedAdvisors);
    return composedAdvisors.length == 0 ? AbstractAutoProxyCreator.DO_NOT_PROXY : composedAdvisors;
}
 
源代码15 项目: eagle   文件: EagleTraceAutoProxyCreator.java
@Override
protected Object createProxy(
        Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setAopProxyFactory(new EagleTraceProxyFactory());
    proxyFactory.copyFrom(this);
    if (!proxyFactory.isProxyTargetClass()) {
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        } else {
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);
    proxyFactory.setFrozen(false);
    injectRefer(beanClass, targetSource);
    return proxyFactory.getProxy(getProxyClassLoader());

}
 
源代码16 项目: es   文件: AopProxyUtils.java
/**
 * 是否代理了多次
 * 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);
    }
}
 
源代码17 项目: dhis2-core   文件: ProxyUtils.java
public static <T> T getProxyTarget( Object proxy )
{
    if ( !AopUtils.isAopProxy( proxy ) )
    {
        throw new IllegalStateException( "Target must be a proxy" );
    }

    TargetSource targetSource = ((Advised) proxy).getTargetSource();
    return getTarget( targetSource );
}
 
/**
 * Identify as bean to proxy if the bean name is in the configured list of names.
 */
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
	if (this.beanNames != null) {
		for (String mappedName : this.beanNames) {
			if (FactoryBean.class.isAssignableFrom(beanClass)) {
				if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
					continue;
				}
				mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
			}
			if (isMatch(beanName, mappedName)) {
				return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
			}
			BeanFactory beanFactory = getBeanFactory();
			if (beanFactory != null) {
				String[] aliases = beanFactory.getAliases(beanName);
				for (String alias : aliases) {
					if (isMatch(alias, mappedName)) {
						return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
					}
				}
			}
		}
	}
	return DO_NOT_PROXY;
}
 
@Override
@Nullable
public final TargetSource getTargetSource(Class<?> beanClass, String beanName) {
	AbstractBeanFactoryBasedTargetSource targetSource =
			createBeanFactoryBasedTargetSource(beanClass, beanName);
	if (targetSource == null) {
		return null;
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Configuring AbstractBeanFactoryBasedTargetSource: " + targetSource);
	}

	DefaultListableBeanFactory internalBeanFactory = getInternalBeanFactoryForBean(beanName);

	// We need to override just this bean definition, as it may reference other beans
	// and we're happy to take the parent's definition for those.
	// Always use prototype scope if demanded.
	BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
	GenericBeanDefinition bdCopy = new GenericBeanDefinition(bd);
	if (isPrototypeBased()) {
		bdCopy.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	}
	internalBeanFactory.registerBeanDefinition(beanName, bdCopy);

	// Complete configuring the PrototypeTargetSource.
	targetSource.setTargetBeanName(beanName);
	targetSource.setBeanFactory(internalBeanFactory);

	return targetSource;
}
 
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
	// 注释 8. 切面 bean 实例化之前执行的方法
	// 根据 beanClass 或者 beanName,组装一个 唯一 key
	Object cacheKey = getCacheKey(beanClass, beanName);

	// beanName 不存在 || 目标堆中不存在这个 bean
	if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
		// 内层判断是否需要进行切面增强,这是个短路操作,判断成功后将跳过后面的操作
		if (this.advisedBeans.containsKey(cacheKey)) {
			return null;
		}
		if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, 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(beanClass, beanName);
	if (targetSource != null) {
		if (StringUtils.hasLength(beanName)) {
			this.targetSourcedBeans.add(beanName);
		}
		// 实际上委派给子类去实现 AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
		// 根据上面的增强方法创建代理
		Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
		this.proxyTypes.put(cacheKey, proxy.getClass());
		return proxy;
	}

	return null;
}
 
源代码21 项目: yes-cart   文件: ShoppingCartFilter.java
/**
 * @param shopService         shop service
 * @param tuplizerPool        pool of tuplizer to manage cookie to object to cookie transformation
 * @param calculationStrategy calculation strategy
 * @param cartCommandFactory  cart command factory
 */
public ShoppingCartFilter(final ShopService shopService,
                          final TargetSource tuplizerPool,
                          final AmountCalculationStrategy calculationStrategy,
                          final ShoppingCartCommandFactory cartCommandFactory) {
    this.shopService = shopService;
    this.tuplizerPool = tuplizerPool;
    this.calculationStrategy = calculationStrategy;
    this.cartCommandFactory = cartCommandFactory;
}
 
/**
 * Create an AOP proxy for the given bean.
 *
 * 注释 8.9 为给定的bean创建AOP代理,实际在这一步中进行切面织入,生成动态代理
 *
 * @param beanClass the class 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(Class<?> beanClass, @Nullable String beanName,
		@Nullable Object[] specificInterceptors, TargetSource targetSource) {

	if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
		AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
	}

	ProxyFactory proxyFactory = new ProxyFactory();
	// 拷贝,获取当前类中的相关属性
	proxyFactory.copyFrom(this);

	// 决定对于给定 bean 是否应该使用 targetClass 而不是他的接口代理
	if (!proxyFactory.isProxyTargetClass()) {
		// 检查 proxyTargetClass 设置以及 preserveTargetClass 属性
		if (shouldProxyTargetClass(beanClass, beanName)) {
			proxyFactory.setProxyTargetClass(true);
		}
		else {
			// 添加代理接口
			evaluateProxyInterfaces(beanClass, 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(getProxyClassLoader());
}
 
源代码23 项目: disconf   文件: PrivateMethodUtil.java
/**
 * spring注入对象的私有方法调用
 * 
 * @param owner
 *            注入的对象
 * @param methodName
 *            私有方法名
 * @param parameterTypes
 *            私有方法参数类型
 * @param parameters
 *            私有方法参数
 * @return 私有方法返回值
 */
@SuppressWarnings({ "rawtypes" })
public static Object invokeMethod(final Object owner,
        final String methodName, final Class[] parameterTypes,
        final Object[] parameters) throws Exception {

    // get class
    final Class ownerclass = owner.getClass();

    // get property
    try {

        @SuppressWarnings("unchecked")
        final Method getTargetClass = ownerclass
                .getMethod("getTargetSource");
        final TargetSource target = (TargetSource) getTargetClass.invoke(
                owner, new Object[] {});
        final Class targetClass = target.getTargetClass();
        @SuppressWarnings("unchecked")
        final Method method = targetClass.getDeclaredMethod(methodName,
                parameterTypes);

        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        final Object targetInstance = target.getTarget();
        return method.invoke(targetInstance, parameters);

    } catch (NoSuchMethodException e) {

        return invokeMethod(owner, 0, methodName, parameterTypes,
                parameters);
        // e.printStackTrace();
    }
}
 
/**
 * Determine a TargetSource for the given target (or TargetSource).
 * @param target target. If this is an implementation of TargetSource it is
 * used as our TargetSource; otherwise it is wrapped in a SingletonTargetSource.
 * @return a TargetSource for this object
 */
protected TargetSource createTargetSource(Object target) {
	if (target instanceof TargetSource) {
		return (TargetSource) target;
	}
	else {
		return new SingletonTargetSource(target);
	}
}
 
protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, final String beanName) {
	Assert.state(getBeanFactory() instanceof DefaultListableBeanFactory,
			"BeanFactory needs to be a DefaultListableBeanFactory");
	final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
	TargetSource ts = new TargetSource() {
		@Override
		public Class<?> getTargetClass() {
			return descriptor.getDependencyType();
		}
		@Override
		public boolean isStatic() {
			return false;
		}
		@Override
		public Object getTarget() {
			return beanFactory.doResolveDependency(descriptor, beanName, null, null);
		}
		@Override
		public void releaseTarget(Object target) {
		}
	};
	ProxyFactory pf = new ProxyFactory();
	pf.setTargetSource(ts);
	Class<?> dependencyType = descriptor.getDependencyType();
	if (dependencyType.isInterface()) {
		pf.addInterface(dependencyType);
	}
	return pf.getProxy(beanFactory.getBeanClassLoader());
}
 
源代码26 项目: spring-analysis-note   文件: ProxyFactoryBean.java
/**
 * Create a new prototype instance of this class'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 && !isProxyTargetClass()) {
		// Rely on AOP infrastructure to tell us what interfaces to proxy.
		Class<?> targetClass = targetSource.getTargetClass();
		if (targetClass != null) {
			copy.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
		}
	}
	copy.setFrozen(this.freezeProxy);

	if (logger.isTraceEnabled()) {
		logger.trace("Using ProxyCreatorSupport copy: " + copy);
	}
	return getProxy(copy.createAopProxy());
}
 
源代码27 项目: spring-analysis-note   文件: AopProxyUtils.java
/**
 * 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;
}
 
/**
 * Determine a TargetSource for the given target (or TargetSource).
 * @param target target. If this is an implementation of TargetSource it is
 * used as our TargetSource; otherwise it is wrapped in a SingletonTargetSource.
 * @return a TargetSource for this object
 */
protected TargetSource createTargetSource(Object target) {
	if (target instanceof TargetSource) {
		return (TargetSource) target;
	}
	else {
		return new SingletonTargetSource(target);
	}
}
 
/**
 * 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 class)
 * @return the generated proxy
 * @see RefreshableScriptTargetSource
 */
protected Object createRefreshableProxy(TargetSource ts, @Nullable Class<?>[] interfaces, boolean proxyTargetClass) {
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTargetSource(ts);
	ClassLoader classLoader = this.beanClassLoader;

	if (interfaces != null) {
		proxyFactory.setInterfaces(interfaces);
	}
	else {
		Class<?> targetClass = ts.getTargetClass();
		if (targetClass != null) {
			proxyFactory.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.beanClassLoader));
		}
	}

	if (proxyTargetClass) {
		classLoader = null;  // force use of Class.getClassLoader()
		proxyFactory.setProxyTargetClass(true);
	}

	DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(ts);
	introduction.suppressInterface(TargetSource.class);
	proxyFactory.addAdvice(introduction);

	return proxyFactory.getProxy(classLoader);
}
 
/**
 * 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.class, this.connectorTargetSource).getProxy(this.beanClassLoader);
	this.connection = (MBeanServerConnection)
			new ProxyFactory(MBeanServerConnection.class, connectionTargetSource).getProxy(this.beanClassLoader);
}