Monday, September 24, 2012

XML less configuration in spring 3 using annotations


Since the release of Spring 3, JavaConfig is part of core module and provides and easy way to configure Spring applications.  In this post I am going to show how you can achieve complete Java based configuration in Spring 3 without any XML files.

Before  we start looking at the code lets look at some basic Spring annotation and their meanings.

@Configuration: It indicates that a class declares one or more Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@Bean: This annotation is applied to methods that create beans in a Spring context. The name of the bean is the method name.

These two annotation are minimum requirement to start with XML less configuration in spring. Let see the code now:



/**
 * This is purely java based configuration and do not uses
 * any XML files.
 */
@Configuration
public class AppConfig {

    /**
     * This creates bean with name testBean. Note that the bean name is method name by default. In
     * this case bean name will be testBean.
     */
    @Bean
    public MyBean testBean() {
        return new TestBean();
    }

    /**
     * You can override the default name providing your own name to bean annotation. In this case
     * bean name will be renamedBean.
     */
    @Bean(name = "renamedBean")
    public AnotherBean anotherBean() {
        return new AnotherBean();
    }

    public static void main(String[] args) {
        // Initialize spring container. Note that we are giving AppConfig.class so that spring loads
        // beans defined in this class
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        System.out.println("calling a bean method");
        // Retrieve the bean from Container by class
        MyBean bean = context.getBean(MyBean.class);

        // Retrieve the bean from Container by name
        // typecase is required
        AnotherBean anotherBean = (AnotherBean) context.getBean("renamedDao");
        bean.helloWorld();
        anotherBean.helloSpring();
    }
}

Yo can also use @ComponentScan annotation to instantiate the beans outside of AppConfig class. Spring IoC scans the the package or class name given as argument to @ComponentScan annotation and instantiates them as beans if they have @Service or @Component annotation.


@Configuration
@ComponentScan("test.package") //scans test.packages for any components and instantiates them a beans
public class AppConfig {

No comments:

Post a Comment