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

public class HelloSpring {

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

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

public class Test {
   public static void main(String[] args) {
      ApplicationContext context = new
      HelloSpring obj = (HelloSpring)
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

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
public class Student{
	private Course course;
	public Course getCourse(){
		return new Course();
spring.xml file
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

	<context:component-scan base-package="com.jtechies"/>
NOTE : <context:component-scan base-package="com.jtechies"/> will scan and load @Configuration bean.