Java Code Examples for org.springframework.aop.framework.ProxyFactory#addInterface()

The following examples show how to use org.springframework.aop.framework.ProxyFactory#addInterface() . 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: ApplicationListenerMethodAdapterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void invokeListenerInvalidProxy() {
	Object target = new InvalidProxyTestBean();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTarget(target);
	proxyFactory.addInterface(SimpleService.class);
	Object bean = proxyFactory.getProxy(getClass().getClassLoader());

	Method method = ReflectionUtils.findMethod(
			InvalidProxyTestBean.class, "handleIt2", ApplicationEvent.class);
	StaticApplicationListenerMethodAdapter listener =
			new StaticApplicationListenerMethodAdapter(method, bean);
	assertThatIllegalStateException().isThrownBy(() ->
			listener.onApplicationEvent(createGenericTestEvent("test")))
		.withMessageContaining("handleIt2");
}
 
Example 2
Source File: EncryptablePropertySourceConverter.java    From jasypt-spring-boot with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> PropertySource<T> proxyPropertySource(PropertySource<T> propertySource) {
    //Silly Chris Beams for making CommandLinePropertySource getProperty and containsProperty methods final. Those methods
    //can't be proxied with CGLib because of it. So fallback to wrapper for Command Line Arguments only.
    if (CommandLinePropertySource.class.isAssignableFrom(propertySource.getClass())
            // Other PropertySource classes like org.springframework.boot.env.OriginTrackedMapPropertySource
            // are final classes as well
            || Modifier.isFinal(propertySource.getClass().getModifiers())) {
        return instantiatePropertySource(propertySource);
    }
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTargetClass(propertySource.getClass());
    proxyFactory.setProxyTargetClass(true);
    proxyFactory.addInterface(EncryptablePropertySource.class);
    proxyFactory.setTarget(propertySource);
    proxyFactory.addAdvice(new EncryptablePropertySourceMethodInterceptor<>(propertySource, propertyResolver, propertyFilter));
    return (PropertySource<T>) proxyFactory.getProxy();
}
 
Example 3
Source File: RemoteExporter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Get a proxy for the given service object, implementing the specified
 * service interface.
 * <p>Used to export a proxy that does not expose any internals but just
 * a specific interface intended for remote access. Furthermore, a
 * {@link RemoteInvocationTraceInterceptor} will be registered (by default).
 * @return the proxy
 * @see #setServiceInterface
 * @see #setRegisterTraceInterceptor
 * @see RemoteInvocationTraceInterceptor
 */
protected Object getProxyForService() {
	checkService();
	checkServiceInterface();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.addInterface(getServiceInterface());
	if (this.registerTraceInterceptor != null ?
			this.registerTraceInterceptor.booleanValue() : this.interceptors == null) {
		proxyFactory.addAdvice(new RemoteInvocationTraceInterceptor(getExporterName()));
	}
	if (this.interceptors != null) {
		AdvisorAdapterRegistry adapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();
		for (int i = 0; i < this.interceptors.length; i++) {
			proxyFactory.addAdvisor(adapterRegistry.wrap(this.interceptors[i]));
		}
	}
	proxyFactory.setTarget(getService());
	proxyFactory.setOpaque(true);
	return proxyFactory.getProxy(getBeanClassLoader());
}
 
Example 4
Source File: RemoteExporter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a proxy for the given service object, implementing the specified
 * service interface.
 * <p>Used to export a proxy that does not expose any internals but just
 * a specific interface intended for remote access. Furthermore, a
 * {@link RemoteInvocationTraceInterceptor} will be registered (by default).
 * @return the proxy
 * @see #setServiceInterface
 * @see #setRegisterTraceInterceptor
 * @see RemoteInvocationTraceInterceptor
 */
protected Object getProxyForService() {
	checkService();
	checkServiceInterface();

	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.addInterface(getServiceInterface());

	if (this.registerTraceInterceptor != null ? this.registerTraceInterceptor : this.interceptors == null) {
		proxyFactory.addAdvice(new RemoteInvocationTraceInterceptor(getExporterName()));
	}
	if (this.interceptors != null) {
		AdvisorAdapterRegistry adapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();
		for (Object interceptor : this.interceptors) {
			proxyFactory.addAdvisor(adapterRegistry.wrap(interceptor));
		}
	}

	proxyFactory.setTarget(getService());
	proxyFactory.setOpaque(true);

	return proxyFactory.getProxy(getBeanClassLoader());
}
 
Example 5
Source File: JndiObjectFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static Object createJndiObjectProxy(JndiObjectFactoryBean jof) throws NamingException {
	// Create a JndiObjectTargetSource that mirrors the JndiObjectFactoryBean's configuration.
	JndiObjectTargetSource targetSource = new JndiObjectTargetSource();
	targetSource.setJndiTemplate(jof.getJndiTemplate());
	String jndiName = jof.getJndiName();
	Assert.state(jndiName != null, "No JNDI name specified");
	targetSource.setJndiName(jndiName);
	targetSource.setExpectedType(jof.getExpectedType());
	targetSource.setResourceRef(jof.isResourceRef());
	targetSource.setLookupOnStartup(jof.lookupOnStartup);
	targetSource.setCache(jof.cache);
	targetSource.afterPropertiesSet();

	// Create a proxy with JndiObjectFactoryBean's proxy interface and the JndiObjectTargetSource.
	ProxyFactory proxyFactory = new ProxyFactory();
	if (jof.proxyInterfaces != null) {
		proxyFactory.setInterfaces(jof.proxyInterfaces);
	}
	else {
		Class<?> targetClass = targetSource.getTargetClass();
		if (targetClass == null) {
			throw new IllegalStateException(
					"Cannot deactivate 'lookupOnStartup' without specifying a 'proxyInterface' or 'expectedType'");
		}
		Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader);
		for (Class<?> ifc : ifcs) {
			if (Modifier.isPublic(ifc.getModifiers())) {
				proxyFactory.addInterface(ifc);
			}
		}
	}
	if (jof.exposeAccessContext) {
		proxyFactory.addAdvice(new JndiContextExposingInterceptor(jof.getJndiTemplate()));
	}
	proxyFactory.setTargetSource(targetSource);
	return proxyFactory.getProxy(jof.beanClassLoader);
}
 
Example 6
Source File: ModelMapTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testAopJdkProxy() throws Exception {
	ModelMap map = new ModelMap();
	ProxyFactory factory = new ProxyFactory();
	Map<?, ?> target = new HashMap<Object, Object>();
	factory.setTarget(target);
	factory.addInterface(Map.class);
	Object proxy = factory.getProxy();
	map.addAttribute(proxy);
	assertSame(proxy, map.get("map"));
}
 
Example 7
Source File: ScopedProxyFactoryBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	if (!(beanFactory instanceof ConfigurableBeanFactory)) {
		throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
	}
	ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;

	this.scopedTargetSource.setBeanFactory(beanFactory);

	ProxyFactory pf = new ProxyFactory();
	pf.copyFrom(this);
	pf.setTargetSource(this.scopedTargetSource);

	Class<?> beanType = beanFactory.getType(this.targetBeanName);
	if (beanType == null) {
		throw new IllegalStateException("Cannot create scoped proxy for bean '" + this.targetBeanName +
				"': Target type could not be determined at the time of proxy creation.");
	}
	if (!isProxyTargetClass() || beanType.isInterface() || Modifier.isPrivate(beanType.getModifiers())) {
		pf.setInterfaces(ClassUtils.getAllInterfacesForClass(beanType, cbf.getBeanClassLoader()));
	}

	// Add an introduction that implements only the methods on ScopedObject.
	ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName());
	pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject));

	// Add the AopInfrastructureBean marker to indicate that the scoped proxy
	// itself is not subject to auto-proxying! Only its target bean is.
	pf.addInterface(AopInfrastructureBean.class);

	this.proxy = pf.getProxy(cbf.getBeanClassLoader());
}
 
Example 8
Source File: ReflectionTestUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setFieldAndGetFieldViaJdkDynamicProxy() throws Exception {
	ProxyFactory pf = new ProxyFactory(this.person);
	pf.addInterface(Person.class);
	Person proxy = (Person) pf.getProxy();
	assertTrue("Proxy is a JDK dynamic proxy", AopUtils.isJdkDynamicProxy(proxy));
	assertSetFieldAndGetFieldBehaviorForProxy(proxy, this.person);
}
 
Example 9
Source File: AopTestUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Foo jdkProxy(Foo foo) {
	ProxyFactory pf = new ProxyFactory();
	pf.setTarget(foo);
	pf.addInterface(Foo.class);
	Foo proxy = (Foo) pf.getProxy();
	assertTrue("Proxy is a JDK dynamic proxy", AopUtils.isJdkDynamicProxy(proxy));
	assertThat(proxy, instanceOf(Foo.class));
	return proxy;
}
 
Example 10
Source File: JaxWsPortProxyFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() {
	super.afterPropertiesSet();

	Class<?> ifc = getServiceInterface();
	Assert.notNull(ifc, "Property 'serviceInterface' is required");

	// Build a proxy that also exposes the JAX-WS BindingProvider interface.
	ProxyFactory pf = new ProxyFactory();
	pf.addInterface(ifc);
	pf.addInterface(BindingProvider.class);
	pf.addAdvice(this);
	this.serviceProxy = pf.getProxy(getBeanClassLoader());
}
 
Example 11
Source File: PersistenceExceptionTranslationAdvisorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected RepositoryInterface createProxy(RepositoryInterfaceImpl target) {
	MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator();
	mpet.addTranslation(persistenceException1, new InvalidDataAccessApiUsageException("", persistenceException1));
	ProxyFactory pf = new ProxyFactory(target);
	pf.addInterface(RepositoryInterface.class);
	addPersistenceExceptionTranslation(pf, mpet);
	return (RepositoryInterface) pf.getProxy();
}
 
Example 12
Source File: RegistrarFactoryBean.java    From BootNettyRpc with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addInterface(interfaze);
    proxyFactory.addAdvice(interceptor);
    proxyFactory.setOptimize(false);
    proxy = proxyFactory.getProxy(classLoader);
}
 
Example 13
Source File: SerializableProxyUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Serializable proxy for the given target.
 * @param target target to proxy
 * @param reference serializable reference 
 * @return a new serializable proxy
 */
public static Object createSerializableProxy(Object target, SerializableReference reference) {
	ProxyFactory pf = new ProxyFactory(target);		
	pf.setExposeProxy(true);		
	pf.setProxyTargetClass(reference.isProxyTargetClass());
	pf.addInterface(SerializableObject.class);
	pf.addAdvice(new SerializableIntroductionInterceptor(reference));
	
	return pf.getProxy(reference.getBeanFactory().getBeanClassLoader());
}
 
Example 14
Source File: ModelMapTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testAopJdkProxyWithMultipleInterfaces() throws Exception {
	ModelMap map = new ModelMap();
	Map<?, ?> target = new HashMap<>();
	ProxyFactory factory = new ProxyFactory();
	factory.setTarget(target);
	factory.addInterface(Serializable.class);
	factory.addInterface(Cloneable.class);
	factory.addInterface(Comparable.class);
	factory.addInterface(Map.class);
	Object proxy = factory.getProxy();
	map.addAttribute(proxy);
	assertSame(proxy, map.get("map"));
}
 
Example 15
Source File: JndiObjectFactoryBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static Object createJndiObjectProxy(JndiObjectFactoryBean jof) throws NamingException {
	// Create a JndiObjectTargetSource that mirrors the JndiObjectFactoryBean's configuration.
	JndiObjectTargetSource targetSource = new JndiObjectTargetSource();
	targetSource.setJndiTemplate(jof.getJndiTemplate());
	targetSource.setJndiName(jof.getJndiName());
	targetSource.setExpectedType(jof.getExpectedType());
	targetSource.setResourceRef(jof.isResourceRef());
	targetSource.setLookupOnStartup(jof.lookupOnStartup);
	targetSource.setCache(jof.cache);
	targetSource.afterPropertiesSet();

	// Create a proxy with JndiObjectFactoryBean's proxy interface and the JndiObjectTargetSource.
	ProxyFactory proxyFactory = new ProxyFactory();
	if (jof.proxyInterfaces != null) {
		proxyFactory.setInterfaces(jof.proxyInterfaces);
	}
	else {
		Class<?> targetClass = targetSource.getTargetClass();
		if (targetClass == null) {
			throw new IllegalStateException(
					"Cannot deactivate 'lookupOnStartup' without specifying a 'proxyInterface' or 'expectedType'");
		}
		Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader);
		for (Class<?> ifc : ifcs) {
			if (Modifier.isPublic(ifc.getModifiers())) {
				proxyFactory.addInterface(ifc);
			}
		}
	}
	if (jof.exposeAccessContext) {
		proxyFactory.addAdvice(new JndiContextExposingInterceptor(jof.getJndiTemplate()));
	}
	proxyFactory.setTargetSource(targetSource);
	return proxyFactory.getProxy(jof.beanClassLoader);
}
 
Example 16
Source File: ModelMapTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testAopJdkProxyWithMultipleInterfaces() throws Exception {
	ModelMap map = new ModelMap();
	Map<?, ?> target = new HashMap<>();
	ProxyFactory factory = new ProxyFactory();
	factory.setTarget(target);
	factory.addInterface(Serializable.class);
	factory.addInterface(Cloneable.class);
	factory.addInterface(Comparable.class);
	factory.addInterface(Map.class);
	Object proxy = factory.getProxy();
	map.addAttribute(proxy);
	assertSame(proxy, map.get("map"));
}
 
Example 17
Source File: JndiObjectFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static Object createJndiObjectProxy(JndiObjectFactoryBean jof) throws NamingException {
	// Create a JndiObjectTargetSource that mirrors the JndiObjectFactoryBean's configuration.
	JndiObjectTargetSource targetSource = new JndiObjectTargetSource();
	targetSource.setJndiTemplate(jof.getJndiTemplate());
	String jndiName = jof.getJndiName();
	Assert.state(jndiName != null, "No JNDI name specified");
	targetSource.setJndiName(jndiName);
	targetSource.setExpectedType(jof.getExpectedType());
	targetSource.setResourceRef(jof.isResourceRef());
	targetSource.setLookupOnStartup(jof.lookupOnStartup);
	targetSource.setCache(jof.cache);
	targetSource.afterPropertiesSet();

	// Create a proxy with JndiObjectFactoryBean's proxy interface and the JndiObjectTargetSource.
	ProxyFactory proxyFactory = new ProxyFactory();
	if (jof.proxyInterfaces != null) {
		proxyFactory.setInterfaces(jof.proxyInterfaces);
	}
	else {
		Class<?> targetClass = targetSource.getTargetClass();
		if (targetClass == null) {
			throw new IllegalStateException(
					"Cannot deactivate 'lookupOnStartup' without specifying a 'proxyInterface' or 'expectedType'");
		}
		Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader);
		for (Class<?> ifc : ifcs) {
			if (Modifier.isPublic(ifc.getModifiers())) {
				proxyFactory.addInterface(ifc);
			}
		}
	}
	if (jof.exposeAccessContext) {
		proxyFactory.addAdvice(new JndiContextExposingInterceptor(jof.getJndiTemplate()));
	}
	proxyFactory.setTargetSource(targetSource);
	return proxyFactory.getProxy(jof.beanClassLoader);
}
 
Example 18
Source File: CommonAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 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 @Nullable 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 19
Source File: TransactionProxyFactoryBean.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * As of 4.2, this method adds {@link TransactionalProxy} to the set of
 * proxy interfaces in order to avoid re-processing of transaction metadata.
 */
@Override
protected void postProcessProxyFactory(ProxyFactory proxyFactory) {
	proxyFactory.addInterface(TransactionalProxy.class);
}
 
Example 20
Source File: TransactionProxyFactoryBean.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * As of 4.2, this method adds {@link TransactionalProxy} to the set of
 * proxy interfaces in order to avoid re-processing of transaction metadata.
 */
@Override
protected void postProcessProxyFactory(ProxyFactory proxyFactory) {
	proxyFactory.addInterface(TransactionalProxy.class);
}