Assign a spring proxy using Java Configuration

27 Views Asked by At

I have this piece of code

<bean id="proxy"
        class="org.springframework.aop.framework.ProxyFactoryBean"
        p:target-ref="john" p:interceptorNames-ref="advisorNames">
    </bean>

    <bean id="documentarist"
        class="com.aop.declarative.Documentarist"
        p:guitarist-ref="proxy" />

I want to do similar configuration using Java Config.

@Bean
    public ProxyFactoryBean factoryBean() {
        ProxyFactoryBean factoryBean = new ProxyFactoryBean();
        factoryBean.setTarget(guitarist());
        factoryBean.setProxyTargetClass(true);
        factoryBean.addAdvisor(pointcutAdvisor());
        return factoryBean;
    }

    @Bean
    public Documentarist documentarist() {
        Documentarist documentarist = new Documentarist();
        documentarist.setGuitarist(guitarist());
        return documentarist;
    }

In this line of code documentarist.setGuitarist(guitarist()); instead of guitarist(), I want to use factoryBean() so the proxied guitarist is injected as we do in xml. How do we do that using Java configuration?

1

There are 1 best solutions below

0
Krishnakumar R On

After experimenting this is the solution I found.

documentarist.setGuitarist((Guitarist) factoryBean().getObject());

Because the ProxyFactoryBean implements FactoryBean, its getObject() returns the Object being proxied. Because it returns Object, it was casted to the correct type.