Example usage for org.springframework.aop.framework ProxyFactoryBean getObject

List of usage examples for org.springframework.aop.framework ProxyFactoryBean getObject

Introduction

In this page you can find the example usage for org.springframework.aop.framework ProxyFactoryBean getObject.

Prototype

@Override
@Nullable
public Object getObject() throws BeansException 

Source Link

Document

Return a proxy.

Usage

From source file:com.ivanzhangwb.interpose.core.InterposeBootStrap.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
    if (interposeClassPathApplicationContext == null) {
        interposeClassPathApplicationContext = new InterposeClassPathApplicationContext(
                this.applicationContext);
    }//from www  .  java  2s  . c o m
    boolean needInterpose = false;
    Class beanClass = bean.getClass();
    do {
        Method[] methods = beanClass.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            if (Interpose.class != null && methods[i].isAnnotationPresent(Interpose.class)
                    && methods[i].equals(ClassUtils.getMostSpecificMethod(methods[i], bean.getClass()))) {
                needInterpose = true;
                handleMethodAnnotation(methods[i]);
            }
        }
        beanClass = beanClass.getSuperclass();
    } while (beanClass != null);

    if (needInterpose) {
        ConfigurableApplicationContext atx = (ConfigurableApplicationContext) interposeClassPathApplicationContext;
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) atx.getBeanFactory();
        ProxyFactoryBean factoryBean = new ProxyFactoryBean();
        factoryBean.setTarget(bean);
        factoryBean.setInterceptorNames(new String[] { InterposeConstants.INTERPOSE_CORE_INTERCEPTOR });
        factoryBean.setBeanFactory(beanFactory);
        return factoryBean.getObject();
    } else {
        return bean;
    }
}

From source file:com.github.lothar.security.acl.jpa.query.AclJpaQuery.java

private AclPredicateTargetSource installAclPredicateTargetSource() {
    synchronized (cachedCriteriaQuery) {
        Predicate restriction = cachedCriteriaQuery.getRestriction();

        if (restriction instanceof Advised) {
            Advised advised = (Advised) restriction;
            if (advised.getTargetSource() instanceof AclPredicateTargetSource) {
                return (AclPredicateTargetSource) advised.getTargetSource();
            }/*w ww.j  a va2s .  c  om*/
        }

        AclPredicateTargetSource targetSource = new AclPredicateTargetSource(em.getCriteriaBuilder(),
                restriction);
        ProxyFactoryBean factoryBean = new ProxyFactoryBean();
        factoryBean.setTargetSource(targetSource);
        factoryBean.setAutodetectInterfaces(true);
        Predicate enhancedPredicate = (Predicate) factoryBean.getObject();
        logger.debug("ACL Jpa Specification target source initialized for criteria {}", cachedCriteriaQuery);

        // install proxy inside criteria
        cachedCriteriaQuery.where(enhancedPredicate);
        return targetSource;
    }
}

From source file:org.codehaus.mojo.hibernate3.HibernateExporterMojo.java

/**
 * Builds a proxy that will respect any configured processor instance if configured. This should only be called on subclasses that end up generated java classes.
 *
 * @param delegate the original Exporter
 * @return an Exporter proxy that will correctly give the processor objects a chance to run after the delegate exporters' start() method's been called.
 *///from  w w  w . j  a  v a2 s. c  o m
protected Exporter buildProcessorAwareExporter(final Exporter delegate) {

    MethodInterceptor interceptor = new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            Method method = invocation.getMethod();
            Object[] objects = invocation.getArguments();

            Object result;
            try {
                result = method.invoke(delegate, objects);
                if (method.getName().contains("start")) {
                    handleComposites();
                    handleProcessor();
                }
                return result;
            } catch (Throwable throwable) {
                getLog().error(throwable);
            }
            return null;

        }
    };

    ProxyFactoryBean bean = new ProxyFactoryBean();
    bean.addAdvice(interceptor);
    bean.setProxyTargetClass(true);
    bean.setBeanClassLoader(delegate.getClass().getClassLoader());
    bean.setAutodetectInterfaces(true);
    bean.setTarget(delegate);
    return (Exporter) bean.getObject();
}

From source file:org.springframework.amqp.rabbit.test.RabbitListenerTestHarness.java

@Override
protected void processListener(MethodRabbitListenerEndpoint endpoint, RabbitListener rabbitListener,
        Object bean, Object adminTarget, String beanName) {
    Object proxy = bean;//from ww  w  .j a v a  2s  . c o m
    String id = rabbitListener.id();
    if (StringUtils.hasText(id)) {
        if (this.attributes.getBoolean("spy")) {
            proxy = Mockito.spy(proxy);
            this.listeners.put(id, proxy);
        }
        if (this.attributes.getBoolean("capture")) {
            try {
                ProxyFactoryBean pfb = new ProxyFactoryBean();
                pfb.setProxyTargetClass(true);
                pfb.setTarget(proxy);
                CaptureAdvice advice = new CaptureAdvice();
                pfb.addAdvice(advice);
                proxy = pfb.getObject();
                this.listenerCapture.put(id, advice);
            } catch (Exception e) {
                logger.error("Failed to proxy @RabbitListener with id: " + id);
            }
        }
    } else {
        logger.info("The test harness can only proxy @RabbitListeners with an 'id' attribute");
    }
    super.processListener(endpoint, rabbitListener, proxy, adminTarget, beanName);
}

From source file:org.springframework.cloud.sleuth.instrument.async.ExecutorBeanPostProcessor.java

Object createThreadPoolTaskExecutorProxy(Object bean, boolean cglibProxy, ThreadPoolTaskExecutor executor) {
    ProxyFactoryBean factory = new ProxyFactoryBean();
    factory.setProxyTargetClass(cglibProxy);
    factory.addAdvice(new ExecutorMethodInterceptor<ThreadPoolTaskExecutor>(executor, this.beanFactory) {
        @Override/*from   w ww.  j ava  2  s . c o  m*/
        Executor executor(BeanFactory beanFactory, ThreadPoolTaskExecutor executor) {
            return new LazyTraceThreadPoolTaskExecutor(beanFactory, executor);
        }
    });
    factory.setTarget(bean);
    return factory.getObject();
}

From source file:org.springframework.cloud.sleuth.instrument.async.ExecutorBeanPostProcessor.java

@SuppressWarnings("unchecked")
Object createProxy(Object bean, boolean cglibProxy, Executor executor) {
    ProxyFactoryBean factory = new ProxyFactoryBean();
    factory.setProxyTargetClass(cglibProxy);
    factory.addAdvice(new ExecutorMethodInterceptor(executor, this.beanFactory));
    factory.setTarget(bean);//from ww w . j a v  a2  s .com
    return factory.getObject();
}

From source file:org.springframework.cloud.sleuth.instrument.messaging.TraceMessagingAutoConfiguration.java

@SuppressWarnings("unchecked")
Object createProxy(Object bean) {
    ProxyFactoryBean factory = new ProxyFactoryBean();
    factory.setProxyTargetClass(true);/*from w  ww .  j a v a  2s  . c o m*/
    factory.addAdvice(new MessageListenerMethodInterceptor(this.kafkaTracing, this.tracer));
    factory.setTarget(bean);
    return factory.getObject();
}

From source file:org.springframework.integration.smpp.util.TestCurrentExecutingMethodAdvice.java

@Test
public void testLoggingTheCurrentlyExecutingMethodName() throws Throwable {
    ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
    proxyFactoryBean.setProxyTargetClass(true);
    proxyFactoryBean.addAdvice(new CurrentMethodExposingMethodInterceptor());
    proxyFactoryBean.setTarget(new TestClassWithAMethod());

    TestClassWithAMethod testClassWithAMethod = (TestClassWithAMethod) proxyFactoryBean.getObject();
    testClassWithAMethod.testMe();/*from w w  w . j a v a  2  s.c om*/
}

From source file:org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.java

@SuppressWarnings("unchecked")
private <T> T lazyBean(Class<T> interfaceName) {
    LazyInitTargetSource lazyTargetSource = new LazyInitTargetSource();
    String[] beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext,
            interfaceName);//w ww.  j  av a 2  s.c o  m
    if (beanNamesForType.length == 0) {
        return null;
    }
    String beanName;
    if (beanNamesForType.length > 1) {
        List<String> primaryBeanNames = Arrays.stream(beanNamesForType)
                .filter(i -> applicationContext instanceof ConfigurableApplicationContext)
                .filter(n -> ((ConfigurableApplicationContext) applicationContext).getBeanFactory()
                        .getBeanDefinition(n).isPrimary())
                .collect(Collectors.toList());

        Assert.isTrue(primaryBeanNames.size() != 0, () -> "Found " + beanNamesForType.length
                + " beans for type " + interfaceName + ", but none marked as primary");
        Assert.isTrue(primaryBeanNames.size() == 1, () -> "Found " + primaryBeanNames.size()
                + " beans for type " + interfaceName + " marked as primary");
        beanName = primaryBeanNames.get(0);
    } else {
        beanName = beanNamesForType[0];
    }

    lazyTargetSource.setTargetBeanName(beanName);
    lazyTargetSource.setBeanFactory(applicationContext);
    ProxyFactoryBean proxyFactory = new ProxyFactoryBean();
    proxyFactory = objectPostProcessor.postProcess(proxyFactory);
    proxyFactory.setTargetSource(lazyTargetSource);
    return (T) proxyFactory.getObject();
}