Saturday 5 April 2014

Example: Spring configuration using AnnotationConfigApplicationContext without XML


Below is the example for Bean configuration using AnnotationConfigApplicationContext.

AnnotationConfigApplicationContext(<Package to scan>) or
AnnotationConfigApplicationContext(@Configuration class with @bean declaration)

We have to make sure that the same beans are not marked @component and also defined in @configuration class



Class with @component annotation

package org.first;

import org.springframework.stereotype.Component;

@Component
public class FirstServiceImpl implements FirstService
{

    public FirstServiceImpl()
    {
    }

    public String printMessage()
    {
        final String s = "--printMessage()---";
        System.out.println(s);
        return s;

    }

    public String messagePrint()
    {
        final String s = "--messagePrint()---";
        System.out.println(s);
        return s;

    }

    public FirstServiceImpl getfirstService()
    {
        return new FirstServiceImpl();
    }
}


Test code


import org.first.FirstService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AOPTest
{

    ApplicationContext ctx = new AnnotationConfigApplicationContext("org.first");

    @Test
    public void testContext()
    {
        final FirstService service = ctx.getBean(FirstService.class);
        service.printMessage();

    }
}

No comments:

Post a Comment