Wednesday, April 19, 2017

Spring Scoped Proxy Beans – Prototype bean into Singleton

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, let’s 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

01
@Component
02
public class RequestProcessor implements Processor {

03
  
04
    @Autowired(required = true)

05
    private Validator validator;
06
  

07
    public Response process(Request request) {
08
        List errorMessages = validator.validate(request);

09
        if (!errorMessages.isEmpty()) {
10
            return null;

11
        }
12
        return null;

13
    }
14
  

15
}

Validator class

01
@Component
02
@Scope(value = "prototype")

03
public class Validator {
04
  

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

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

09
    }
10
  

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

13
        return errorMessages;
14
    }

15
  
16
}

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.

01
<?xml version="1.0" encoding="UTF-8"?>
02

03
04

05
06

07
08
  

09
    <context:annotation-config />
10
  

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

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

01
@ContextConfiguration
02
@RunWith(SpringJUnit4ClassRunner.class)

03
public class RequestProcessorTest {
04
  

05
    @Autowired
06
    private Processor processor;

07
  
08
    @Test

09
    public void testProcess() {
10
        for (int i = 0; i < 10; i++) {

11
            Response response = processor.process(new Request());
12
            assertNull(response);

13
        }
14
    }

15
  
16
}

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. 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.

01
@Component
02
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")

03
public class Validator {
04
  

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

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

09
    }
10
  

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

13
        return errorMessages;
14
    }

15
  
16
}


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 cleaner as I don’t have to make my class abstract and it makes unit testing of RequestProcessor class easier.

No comments: