org.springframework.aop.TargetSource Java Examples

The following examples show how to use org.springframework.aop.TargetSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AopProxyUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 —
 * 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;
}
 
Example #2
Source File: AutoProxyCreatorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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;
	}
}
 
Example #3
Source File: AdvisedSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: ProxyFactoryBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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));
	}
}
 
Example #5
Source File: EclairProxyCreator.java    From eclair with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: EagleTraceAutoProxyCreator.java    From eagle with Apache License 2.0 6 votes vote down vote up
@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());

}
 
Example #7
Source File: AopProxyUtils.java    From phone with Apache License 2.0 6 votes vote down vote up
/**
 * 是否代理了多次
 * 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);
    }
}
 
Example #8
Source File: AutoProxyCreatorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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;
	}
}
 
Example #9
Source File: AbstractSingletonProxyFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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;
}
 
Example #10
Source File: ProxyFactoryBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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));
	}
}
 
Example #11
Source File: AbstractAutoProxyCreator.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: AdvisedSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #13
Source File: AbstractSingletonProxyFactoryBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source File: AbstractAutoProxyCreator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: AopProxyUtils.java    From es with Apache License 2.0 6 votes vote down vote up
/**
 * 是否代理了多次
 * 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);
    }
}
 
Example #16
Source File: AutoProxyCreatorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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;
	}
}
 
Example #17
Source File: AbstractAutoProxyCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
	Object cacheKey = getCacheKey(beanClass, beanName);

	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 targetSource = getCustomTargetSource(beanClass, beanName);
	if (targetSource != null) {
		if (StringUtils.hasLength(beanName)) {
			this.targetSourcedBeans.add(beanName);
		}
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
		Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
		this.proxyTypes.put(cacheKey, proxy.getClass());
		return proxy;
	}

	return null;
}
 
Example #18
Source File: AbstractAdvisorAutoProxyCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
		Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {

	List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
	if (advisors.isEmpty()) {
		return DO_NOT_PROXY;
	}
	return advisors.toArray();
}
 
Example #19
Source File: AbstractSingletonProxyFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #20
Source File: MBeanServerConnectionFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: ProxyUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T getTarget( TargetSource targetSource )
{
    try
    {
        return (T) targetSource.getTarget();
    }
    catch ( Exception e )
    {
        throw new IllegalStateException( e );
    }
}
 
Example #22
Source File: ZebraRoutingDataSource.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource customTargetSource)
      throws BeansException {
	Method[] declaredMethods = beanClass.getDeclaredMethods();
	for (Method declaredMethod : declaredMethods) {
		if (pointcut.match(declaredMethod, beanClass)) {
			Advised advised = this.advisedMap.get(beanName);
			if (advised != null) {
				Advisor[] advisors = advised.getAdvisors();
				boolean added = false;
				for (int i = 0; i < advisors.length; i++) {
					if (advisors[i].getAdvice() instanceof TransactionInterceptor) {
						advised.addAdvisor(i, this);
						added = true;
						break;
					}
				}
				if (!added) {
					advised.addAdvisor(this);
				}
				return DO_NOT_PROXY;
			}
			return new Object[] { this };
		}
	}
	return DO_NOT_PROXY;
}
 
Example #23
Source File: CommonAnnotationBeanPostProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 Class<?> getTargetClass() {
			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);
	}
	ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory ?
			((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() : null);
	return pf.getProxy(classLoader);
}
 
Example #24
Source File: PrivateMethodUtil.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example #25
Source File: PackageAutoProxyCreator.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
/**
 * Identify as bean to proxy if the bean name is in the configured base package.
 */
protected Object[] getAdvicesAndAdvisorsForBean(final Class<?> beanClass, final String beanName,
		final TargetSource targetSource) {
	if (this.basePackage != null) {
		if (beanClass != null && beanClass.getPackage() != null
				&& beanClass.getPackage().getName().equals(basePackage)) {
			return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
		}
	}
	return DO_NOT_PROXY;
}
 
Example #26
Source File: InjectCDIBeanPostProcessor.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Object beanToInject = bean;
    if (BeanProvider.isActive()) {
        // Spring may wrap objects in a proxy, for example if a bean is marked as cached. In this case, the proxy
        // will not have the fields we want to (potentially) inject. Note that we are injecting by directly modifying
        // fields, not calling setter methods that the proxy object could wrap. Instead, attempt to find the source
        // object that the proxy is wrapping and perform the injection on that object instead. Log a warning if we
        // can't find the source object.
        if (AopUtils.isAopProxy(bean)) {
            boolean updated = false;
            if (bean instanceof Advised) {
                TargetSource source = ((Advised) bean).getTargetSource();
                if (source != null) {
                    try {
                        beanToInject = source.getTarget();
                        updated = true;
                    } catch (Exception e) {
                        // ignore -- we'll log below
                    }
                }
            }
            if (!updated) {
                log.warn("Unable to retrieve target from proxy bean {}. Injection will not be performed for bean {}.", bean, beanName);
            }
        }
        BeanProvider.injectFields(beanToInject);
    } else {
        log.warn("BeanProvider not initialized yet. Non-prototype beans will not have dependency injection performed on them.");
    }
    return bean;
}
 
Example #27
Source File: BeanNameAutoProxyCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #28
Source File: MBeanServerConnectionFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #29
Source File: AbstractAdvisorAutoProxyCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
	List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
	if (advisors.isEmpty()) {
		return DO_NOT_PROXY;
	}
	return advisors.toArray();
}
 
Example #30
Source File: ProxyFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a proxy for the specified {@code TargetSource} that extends
 * the target class 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.getTargetClass() == null) {
		throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class");
	}
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTargetSource(targetSource);
	proxyFactory.setProxyTargetClass(true);
	return proxyFactory.getProxy();
}