Sunday 18 November 2012

Spring Bean XML To Annotation Configuration

Here is an example of converting an XML based bean configuration to a annotation based configuration.

Assuming an XML files contain the following:
<bean id="localeChangeInterceptor"
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>
<bean id="handlerMapping"
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="interceptors">
       <ref bean="localeChangeInterceptor" />
   </property>
</bean>
The second beans refers to the first one for initialization.

The corresponding Java with annotation configuration is:
@Configuration
public class MyConfig {

    // ...

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result
            = new LocaleChangeInterceptor();

        result.setParamName("lang");

        return result;

    }

    @Bean
    public DefaultAnnotationHandlerMapping handlerMapping() {

        DefaultAnnotationHandlerMapping result
            = new DefaultAnnotationHandlerMapping();

        Object[] interceptors = {
            localeChangeInterceptor()
        };

        result.setInterceptors(interceptors);

        return result;

    }

}

More Spring related posts here.

No comments:

Post a Comment