Spring Java Configuration Example

In this example, we will use Spring JavaConfig to define a bean and register it in Spring IoC container.

JavaConfig is based on @Configuration annotated classes and @Bean annotated methods

 

1. Technologies used

  • Spring 3.2.8.RELEASE
  • Maven 3.0.5
  • Eclipse 4.2
  • JDK 1.6

 

2. Project structure

Spring-JavaConfig-1

 

3. Project dependencies

 

4. Define Spring bean

We create a simple class that we want to define as a Spring bean.

File : HelloWorld

 

Then, we will use @Configuration and @Bean annotations to define our class as a bean managed by Spring IoC container.

File : ApplicationConfig

Annotating ApplicationConfig with @Configuration indicates that this class will be used as a source of bean definitions.

Annotating helloWorld() method with @Bean indicates that this method instantiates and configures a new objects of HelloWorld class to be managed by Spring IoC container.

Equivalent configuration in XML :

 

We can notice that ApplicationConfig plays the same role as <beans /> element.

And @Bean is an analog of the <bean /> element.

 

5. Test It

To load Spring IoC container, we use AnnotationConfigApplicationContext as shown below :

 

Output :

Hello Walid!

 

Download source code

 

Reference