Spring Scoped Proxy Beans – An Alternative to Method Injection

Few months back, I wrote on JavaLobby about how you can use Method Injection in scenarios where bean lifecycles are different i.e. you want to inject a non-singleton bean inside a singleton bean. For those of you who are not aware of Method Injection, it allows you to inject methods instead of objects in your class. Method Injection is useful in scenarios where you need to inject a smaller scope bean in a larger scope bean. For example, you have to inject a prototype bean inside an singleton bean , on each method invocation of Singleton bean. Just defining your bean prototype, does not create new instance each time a singleton bean is called because container creates a singleton bean only once, and thus only sets a prototype bean once. So, it is completely wrong to think that if you make your bean prototype you will get  new instance each time prototype bean is called.

To make this problem more concrete, lets consider we have to inject a validator instance each time a RequestProcessor bean is called. I want validator bean to be prototype because Validator has a state like a collection of error messages which will be different for each request.

RequestProcessor class

public class RequestProcessor implements Processor {

    @Autowired(required = true)
    private Validator validator;

    public Response process(Request request) {
        List errorMessages = validator.validate(request);
        if (!errorMessages.isEmpty()) {
            return null;
        return null;


Validator class

@Scope(value = "prototype")
public class Validator {

    private List<String> errorMessages = new ArrayList<String>();

    public Validator() {
        System.out.println("New Instance");

    public List<String> validate(Request request) {
        errorMessages.add("Validation Failed");
        return errorMessages;


Because I am using Spring annotations, the only thing I need specify in xml is to activate annotation detection and classpath scanning for annotated components.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:annotation-config />

	<context:component-scan base-package="com.shekhar.spring.scoped.proxy"></context:component-scan>

Now lets write a test to see how many instances of prototype bean gets created when we call the processor 10 times.

public class RequestProcessorTest {

    private Processor processor;

    public void testProcess() {
        for (int i = 0; i < 10; i++) {
            Response response = processor.process(new Request());


If you run this test, you will see that only one instance of validator bean gets created as “New Instance” will get printed only once. This is because container creates RequestProcessor bean only once, and thus only sets Validator bean once and reuses that bean on each invocation of process method.

One possible solution for this problem is to use Method Injection which I have already talked about in my JavaLobby article. I didn’t liked method injection approach because it imposes restriction on your class i.e. you have to make your class abstract. In this blog, I am going to talk about the second approach for handling such a problem. The second approach is to use Spring AOP Scoped proxies which injects a new validator instance each time RequestProcessor bean is called. To make it work, the only change you have to do is to specify proxyMode in Validator class.

@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
public class Validator {

    private List<String> errorMessages = new ArrayList<String>();

    public Validator() {
        System.out.println("New Instance");

    public List<String> validate(Request request) {
        errorMessages.add("Validation Failed");
        return errorMessages;


There are four possible values for proxyMode attribute.I have used TARGET_CLASS which creates a class based proxy. This mode requires that you have CGLIB jar in your classpath.If you run your test again you will see that 10 instances of Validator class will be created. I found this solution more cleaner as I don’t have to make my class abstract and it makes unit testing of RequestProcessor class easier.

23 thoughts on “Spring Scoped Proxy Beans – An Alternative to Method Injection”

  1. Hi
    Thanks for this interesting post. A very simple and clean solution.

    Two minor remarks:

    There is no need to add context:annotation-config if you use context:component-scan. From the documentation: ” This tag implies the effects of the ‘annotation-config’ tag”

    There is a constant for the string “prototype”, I use to prevent typos.
    @Scope(value = BeanDefinition.SCOPE_PROTOTYPE)

    Thanks again for the the informative blog posts.

  2. Ok, it’s worked.
    But what should I do if I need to have an access to some singleton-service inside Validator? For example – to validate throw the database.
    I think that I just should add a class member like “@Autowired DBService dbService;” into the Validator class. But It’s not worked. I think that PROXY-object will be created before processing of annotations of Validator’s fields – so it appears in not-inited state.
    What I’m doing wrong?

  3. Hey, one quick question. Why does my class has to be ‘abstract’ in order to use method-injection method. Is it in Spring documentation or is it from your own experience? I have been able to use method-injection quite cleanly without any restrictions on my class.

    Please let me know.


  4. An easier way to do this is by using javax.inject.Provider (JSR330).
    If you need a bean of a different scope, lets say a bean named Bean1, you just have to add a dependency like this :

    private javax.inject.Provider bean1Provider;

    And when you need an instance of Bean1 :

    If Bean1 has a scope singleton, you will always get the same, with a scope prototype, you will always have a new one. And you can use it with other scopes like request and session.
    It’s magic…

  5. Great article, I was looking for inbuilt support for this in spring, rather than accessing/autowiring spring container, that I have used earlier.

    I liked this approach
    @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = “prototype”)
    over accession container ApplicationContext.

    Can you advise me regarding performance cost for using both approach, as creating proxy or CGLIB class file weaving could have significant performance cost?


  6. Nice article Shekhar.
    One doubt. Where exactly the new instance of validator is created.
    Is it at every execution of — validator.validate(request);

  7. Hi, how do i remove the proxied instance of bean in some other java class in the war layer? I want to do something like this:

    HttpSession session = request.getSession();
    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());

  8. HI
    Thanks for the nice article.
    I am facing a issue.
    Scenario :
    I able to get new object every time inside the singleton bean (that’s I want). but there is property inside the Class which i want to set by using setter is always be null even after i assign new MyObject() in the constructor This i came to know that when i debug proxy object contains the null reference as well as calling getter.
    Sample Class looks like

    @Scope(scopeName=ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode=ScopedProxyMode.TARGET_CLASS)
    public class MyPublisherClass implements Runnable, ApplicationEventPublisherAware, MyPublisherInterface {

    private ApplicationEventPublisher applicationEventPublisher = null;

    private MyObject myObject;
    public void setApplicationEventPublisher(
    ApplicationEventPublisher applicationEventPublisher) {
    this.applicationEventPublisher = applicationEventPublisher;
    public void run() {

    this.applicationEventPublisher.publishEvent(new MyEvent(this, myObject));

    public void setMyObject (MyObject myObject ) {
    this.myObject = myObject ;


    public class MyService{
    private MyPublisherClass myPublisherClass ;

    public void myMethod(){
    myPublisherClass .setMyObject (new MyObject ())

    Kindly suggest the same

  9. @Shekhar: I was looking for the answer how you can inject a Prototype bean inside a singleton bean , for Example Class A is singleton and Class B is Prototype . now i want to inject B into A as a prototype bean ..
    I am looking annotation way .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: