Saturday, 5 April 2014

Example : Spring context:component-scan and @Component

Automatic Component scanning is useful in defining beans and autowiring them without defining them in an .xml file


Below is the example  with xml and  and beans annotated

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan  base-package="org.first" />
</beans>


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.support.ClassPathXmlApplicationContext;

public class AOPTest
{

    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

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

    }
}

No comments:

Post a Comment