Spring bean java based configuration using @Configuration and @Bean
In the previous example we have
seen how to configure a bean in the xml based configuration file. In spring 3, we got another alternative solution, we can move all
xml based configurations to java based configurations.
In this page, you can see an example for how to configure a bean using java based configuration. We have created a maven
project, and here is the sample pom.xml file and spring dependencies. Whe have added a new dependency called cglib to support java based
configurations:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringJavaBasedConfig</groupId>
<artifactId>SpringJavaBasedConfig</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<spring.version>3.2.0.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
</project>
|
Here is very basic interface:
package com.java2novice.bean;
public interface MyColor {
public void printColor();
}
|
And its implementation class:
package com.java2novice.bean;
public class RedColor implements MyColor{
@Override
public void printColor() {
System.out.println("It is red in color...");
}
}
|
Now here comes the java based configuration file. This class is equivalent of xml based configuration file. You must annotate
the class with @Configuration. The bean declaration can be achieved by using @Bean annotation.
package com.java2novice.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.java2novice.bean.MyColor;
import com.java2novice.bean.RedColor;
@Configuration
public class MyAppConfig {
@Bean(name="myColorBean")
public MyColor getMyColors(){
return new RedColor();
}
}
|
Project structure snapshot:

Here is the demo class:
package com.java2novice.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.java2novice.bean.MyColor;
import com.java2novice.config.MyAppConfig;
public class SpringDemo {
public static void main(String a[]){
ApplicationContext context
= new AnnotationConfigApplicationContext(MyAppConfig.class);
MyColor color = (MyColor) context.getBean("myColorBean");
color.printColor();
}
}
|
|