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.

Monday, April 10, 2017

Why sort() and binarySearch() methods are exists on Collections rather than Collection?

We call sort() and binarySearch() on Collections rather than CollectionBecause, Collection could not have concrete methods because it is an interface. 

😄😄😄

How to write immutable class?

We can create a immutable classes in different ways. The below strategy is used as a common strategy to create it.

1. Set all the properties of on object in the constructor.
2. Mark all of the instance variables private and final.
3. Don't define any setter methods.
4. Don't allow referenced mutable objects to be modified or accessed directly.
5. Prevent methods from being overridden.

The first rule defines how we create the immutable object, by passing the information
to the constructor, so that all of the data is set upon creation.

The second and third rules are straightforward, as they stem from proper encapsulation. If the instance variables are private and final , and there are no setter methods, then there is no direct way to change the property of an object. All references and primitive values contained in the object are set at creation and cannot be modified.

Why java interfaces having private static final variables?

public: for the accessibility across all the classes, just like the methods present in the interface
static: as interface cannot have an object, the interfaceName.variableName can be used to reference it or directly the variableName in the class implementing it.
final: to make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur in the current value of the var, which is why only one time initialization is permitted.

Sunday, April 9, 2017

Spring: Make an Externally Created Object Available to Beans in applicationContext.xml


If your Spring beans need access to an object that is not created by Spring itself, you can “inject” it into the context by using a static parent context and registering the object with it. Beans can then reference it just as if it was defined in the application context file.

Java: Configure ApplicationContext with an Injected Bean

1
2
3
4
5
6
7
8
9
10
11
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
 
Object externalyDefinedBean = ...;
GenericApplicationContext parentContext = new StaticApplicationContext();
parentContext.getBeanFactory().registerSingleton("injectedBean", externalyDefinedBean);
parentContext.refresh();   // seems to be required sometimes
 
ApplicationContext context = new FileSystemXmlApplicationContext(springConfigs, parentContext);

Xml: Make Use of It

1
2
3
4
<bean id="springBean" class="your.SpringBeanType">
   <!-- Note: The injectedBean is defined outside of Spring config -->
   <property name="someProperty" ref="injectedBean" />
</bean>



Reference: https://theholyjava.wordpress.com/2011/10/11/spring-make-an-externally-created-object-available-to-beans-in-applicationcontext-xml/