Monday, June 11, 2012

Spring Session Scope Bean

Since HTTP stateless, in a web application, a typical way to keep an user states across multiple requests is through HttpSession. However, doing it this way makes your application has tight dependency on HttpSession and its application container. With Spring, carrying states through multiple request can be done through its session scoped bean. It is cleaner and more flexible. Spring session scoped bean is very easy setup, I will try to explain it in a couple steps.

Scenario: Whenever an user enters your site, he is asked to pick a theme to use when navigating your site.
Solution: Store user's selection using Spring Session scoped bean

1. Annotate your bean

@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserSelection{
   private String selectedTheme;
   //and other session values

   public void setSelectedTheme(String theme){

   public String getSelectedTheme(){
       return this.selectedTheme;


2. Inject your session scoped bean

public class SomeController{
   private UserSelection userSelection;

   public void setUserSelection(UserSelectio userSelection){

   public void saveThemeChoice(@RequestParam String selectedTheme){

   public String doOperationBasedOnTheme(){
          String theme=userSelection.selectedTheme();
          //operation codes

In above code snippet, Although 'SomeController' has scope of singleton(default scope of Spring bean), each session will have its own instance of UserSelection. Spring will make the judgement, and inject a new instance of UserSelection if the request is a new session.

Required jars

Besides spring library, aopalliance and cglib jar are also required

Monday, June 4, 2012

Spring Custom Converter

Recently I ran into a problem where Spring would automatically convert comma separated String into String array, and quick search in google, I found people have the same problem on

Read more about Spring Converter

Just a summary of the solution.

1. Create Custom Converter for String to String[]

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

public class CustomStringToArrayConverter implements Converter{
    public String[] convert(String source) {
        return StringUtils.delimitedListToStringArray(source, ";");

2. Register the Custom Conveter.

specify this conversion service bean in your configuration: