Close

Spring - Injecting a Bean as a class based Proxy Object

[Updated: Mar 5, 2016, Created: Mar 5, 2016]

This is another way to solve injecting a narrower scoped bean into wider scoped bean problem.

We need to inject a proxy object that exposes the same public interface as the original scoped object.

Spring uses CGLIB to create the proxy object.

The proxy object delegates method calls to the real object.

Each access of underlying prototype object causes a new object to be created.



Configuring the Scoped Proxy for Prototype bean

@Configuration
public class AppConfig {

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
           proxyMode = ScopedProxyMode.TARGET_CLASS)
    public MyPrototypeBean prototypeBean () {
        return new MyPrototypeBean();
    }

    @Bean
    public MySingletonBean singletonBean () {
        return new MySingletonBean();
    }
}

In above examples proxyMode=ScopedProxyMode.TARGET_CLASS causes an AOP proxy to be injected at the target injection point. The default proxyMode is ScopedProxyMode.NO.

Another possible value, ScopedProxyMode.INTERFACES creates JDK dynamic proxy (instead of class based CGLIB proxy) which can only take the target bean's interface types.



Autowiring The prototype bean into Singleton bean

public class MySingletonBean {

    @Autowired
    private MyPrototypeBean prototypeBean;

    public void showMessage(){
        System.out.println("Hi, the time is "+prototypeBean.getDateTime());
    }
}



Client code

  AnnotationConfigApplicationContext context =
                            new AnnotationConfigApplicationContext(AppConfig.class);
    MySingletonBean bean = context.getBean(MySingletonBean.class);
    bean.showMessage();
    Thread.sleep(1000);

    bean = context.getBean(MySingletonBean.class);
    bean.showMessage();


Output:

Hi, the time is 2016-03-05T13:40:06.003
Hi, the time is 2016-03-05T13:40:07.060

Different time above shows that a new prototype bean instance is created each time.



Example Project

Dependencies and Technologies Used:

  • Spring Context 4.2.4.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.0.4

Scoped Proxy Example Select All Download
  • scoped-proxy-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also