Home > Spring 3 > Spring 3 Enable Annotation based Configuration

Spring 3 Enable Annotation based Configuration

We can enable annotation based bean configuration by including the “context:annotation-config” tag in the Spring XML based configuration file. Note, the “context:component-scan” tag specifies the package directory to be scanned for the annotation configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<context:annotation-config />
	<context:component-scan base-package="sample" />
</beans>

The following code demonstrates the annotation configuration with the Spring XML configuration above. The Spring scans the classes under the sample package and finds classes with @Component or its specialized annotation and register them as a bean. Then, the Spring wires the beans by looking at @Autowired annotation. In the following case, the instance (singleton by default) of Dependency is wired with the instance variable “dependency” of Target instance. The out put from the following code is “sample.Dependency”.

package sample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationTest {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "application-config.xml" });
		Target target = context.getBean(Target.class);
		System.out.println(target.toString());
	}
}

package sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Target {
	@Autowired
	private Dependency dependency;
	@Override
	public String toString() {
		return dependency.toString();
	}
}

package sample;
import org.springframework.stereotype.Component;
@Component
public class Dependency {
	@Override
	public String toString() {
		return Dependency.class.getName();
	}
}

Very neat indeed!

Categories: Spring 3
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment