Home Spring Spring3 The @configuration annotation example in Spring 3.0 Framework
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

The @configuration annotation example in Spring 3.0 Framework

Advertisement
The @configuration annotation allows the developers to configure the beans in the Java class itself.

@configuration annotation in Spring 3

     

In the last section we developed the .xml file to configure the IOC (Spring Container). In this section we will learn another method for configuring the Spring 3 IOC, which is through the Java configuration annotation @configuration. The @configuration annotation is code centric and can be used in place of xml configuration file. 

Two way to configure Spring IOC container

a) xml file: Developer can define the bean configuration in xml file and then instruct the Spring to use the xml file to configure the beans. The xml file configuration method is targeted to infrastructure providers.

b) Annotation: The @configuration spring annotation can also be used to configure the Spring IOC container. Here programmer add the @configuration to the Java class and this class is considered as special configuration class. The @configuration annotation method is targeted the developers.  This is pure-java approach to configure the Spring IoC Container. The @Bean  tag is used to define the bean, and the Spring framework executes the method and then register the object returned. By default the name of the method is used as the bean name.

Step 1:

Download the asm-3.2 from http://forge.ow2.org/project/showfiles.php?group_id=23&release_id=3334 and the add the jar file into project workspace.

Step 2:

Download cglib from http://cglib.sourceforge.net/ and then add the jar file into project workspace. Above jar files are required to work with  @configuration annotation. These are runtime code generation library used by the Spring 3.0 framework.

Step 3:

Creating the configuration file: Create a new java file (Spring3HelloWorldConfig.java) in net.roseindia package. This file is used to programmatically configure the beans in the application. In our example we will configure Spring3HelloWorld bean. Here is the code of Spring3HelloWorldConfig.java:

package net.roseindia;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

 

@Configuration

public class Spring3HelloWorldConfig {

public @Bean Spring3HelloWorld spring3HelloWorld() {

return new Spring3HelloWorld();

}

}

The @configuration spring annotation configures as special class to be used by the Spring IoC to configure beans. The @Bean annotation instruct the IoC container to execute the function spring3HelloWorld() function and register the returned class with the name spring3HelloWorld. Now we will see how to configure the IoC container and retrieve the spring3HelloWorld  bean.

Step 4:

Now create a new java class (Spring3HelloWorldConfigTest.java) and add the following code:

package net.roseindia;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Spring3HelloWorldConfigTest {

public static void main(String[] args) {

//Initialize IoC Container

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(

Spring3HelloWorldConfig.class);

System.out.println("Calling Bean method: sayHello()");

//Retrieve the bean from Container

Spring3HelloWorld myBean = (Spring3HelloWorld) context

.getBean("spring3HelloWorld");

myBean.sayHello();

}

}

Following code initializes the Spring IoC and configures the beans defined in the Spring3HelloWorldConfig class.

//Initialize IoC Container

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(

Spring3HelloWorldConfig.class);

To retrieve the bean from context we can use the following code:

Spring3HelloWorld myBean = (Spring3HelloWorld) context

.getBean("spring3HelloWorld");

Step 5:

To run the example open Spring3HelloWorldConfigTest.java in Eclipse editor window, right click and then select Run As -> Java application. This will execute the code and following output will be displayed on the console.

Jan 2, 2010 2:50:22 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@c1b531:
startup date [Sat Jan 02 14:50:22 IST 2010]; root of context hierarchy

Jan 2, 2010 2:50:22 PM org.springframework.context.annotation.ConfigurationClassEnhancer enhance

INFO: Successfully enhanced net.roseindia.Spring3HelloWorldConfig; enhanced class name is:
net.roseindia.Spring3HelloWorldConfig$$EnhancerByCGLIB$$196e06e4

Jan 2, 2010 2:50:22 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1888759: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,
org.springframework.context.annotation.internalAutowiredAnnotationProcessor,
org.springframework.context.annotation.internalRequiredAnnotationProcessor,
org.springframework.context.annotation.internalCommonAnnotationProcessor,
spring3HelloWorldConfig,spring3HelloWorld]; root of factory hierarchy

Calling Bean method: sayHello()

Hello Spring 3.0

 

In this section we learned about the @configuration annotation. In the next section we will learn the architecture of Spring 3 Framework.

Download Code

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 2, 2010

Ask Questions?    Discuss: The @configuration annotation example in Spring 3.0 Framework   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Tom
June 8, 2011
Spring tutorial

Very good
swathi
August 24, 2011
spring

good
Marco
November 21, 2011
Not working

This Tutorial doesnt work did everything but cant load the beanclass. YES i but the neccessary libs in the build folder. but the tell he overwrites a method. DebuggingCloserWriter overwrites final method visit
user123
December 26, 2011
@configuration annotation in Spring 3

This example works with asm-debug-all-3.2.jar but fail when using asm-debug-all-4.0.jar
Pankaj Mishra
January 18, 2012
Error while running code

I got the error message while running that above code.... ===================================================== log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment). log4j:WARN Please initialize the log4j system properly. Exception in thread "main" java.lang.IllegalStateException: Cannot load configuration class: com.ericsson.Spring3HelloWorldConfig at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:313) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:197) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:620) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446) at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:73) at com.ericsson.Spring3HelloWorldConfigTest.main(Spring3HelloWorldConfigTest.java:9) Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(Z)V at net.sf.cglib.core.DebuggingClassWriter.<init>(DebuggingClassWriter.java:47) at net.sf.cglib.core.DefaultGeneratorStrategy.getClassWriter(DefaultGeneratorStrategy.java:30) at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24) at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216) at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:117) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104) at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69) at org.springframework.context.annotation.ConfigurationClassEnhancer.newEnhancer(ConfigurationClassEnhancer.java:136) at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:109) at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:303) ... 6 more
Niraj
January 8, 2013
Feedback

Appreciate your effort. Very much useful.
Mohana Jeevanandam
December 30, 2011
@configuration annotation in Spring 3

doesn't make code tight coupling..? if we keep that in IOC in XML form, its deployment free for some kind of change management right?.
DMCA.com