Spring Java Configuration

Spring java configuration is a third way of doing Dependency Injection (DI) other than XML and Annotations. It is introduced in Spring 3.0, uses java syntax instead of XML. There are two main annotation used by Spring Java Configuration

  • @Configuration Annotating a class with @Configuration indicate that the class can be used by the Spring IoC container as a source of bean definitions.
  • @Bean annotation indicate Spring that method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.

@Configuration and @Bean Example


HelloSpring.java file
package com.jtechies;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation
		.Configuration;

@Configuration
public class HelloSpring {

	   @Bean
	   public String getMessage(){
	      return "Hello Spring !!!";
	   }
}
Test.java File
package com.jtechies;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation
		.AnnotationConfigApplicationContext;

public class Test {
   public static void main(String[] args) {
      ApplicationContext context = new
      	AnnotationConfigApplicationContext
      	(HelloSpring.class);
      HelloSpring obj = (HelloSpring)
      	context.getBean(HelloSpring.class);
      System.out.println(obj.getMessage());
   }
}
Output
Hello Spring !!!
NOTE : Once your configuration classes are defined, you can load & provide them to Spring container using AnnotationConfigApplicationContext as shown in above Test.java file.

Mixing Configuration Style: XML And @Configuration

@Configuration
@ComponentScan("com.jtechies")
public class MyClass{

}
NOTE :@ComponentScan("com.jtechies") is equivalent to <context:component-scan base-package="com.jtechies"/> in XML file.

You can also use XML dependencies in @Configuration like :
Student.java file
@Configuration
public class Student{
	
	@Autowired
	private Course course;
	
	@Bean
	public Course getCourse(){
		return new Course();
	}
}
spring.xml file
<?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:component-scan base-package="com.jtechies"/>
	
</beans>
NOTE : <context:component-scan base-package="com.jtechies"/> will scan and load @Configuration bean.