Java Based Configuration in Spring

Till now, we have done the configuration using the XML file. Now, In this tutorial, we will see how can we do configuration using Java in Spring Framework.

Configuration of Spring Beans is required so that the container can create an object i.e we can implement the Inversion of Control feature of the spring framework. Using XML-based configuration is a good idea, but if you find writing XML files tiresome then Don’t worry, because Spring 3.1 came up with Java-based Configuration.

In order to go ahead let us first take a brief view on  @Configuration @Bean annotation.

@Configuration & @Bean

According to the Documented Definition: @Configuration annotation indicates that a class declares one or more @Bean methods and may be processed by the spring container to generate bean definitions and service requests for those beans at runtime.

Instead of writing the bean configuration in the XML file. We will write in a Java class file and the Spring container will take care of creating the object.

@Bean

In the XML file, we have used <bean/> element to declare the bean and now instead of this, we will use @Bean annotation on the method. To know more about Bean in Spring check this article What is Spring Bean Definition & Spring Bean Scope?

Let us look at an example to have a clear understanding of Java-based Configuration.

Example of Java-Based Configuration

In this example, we will create an Employee class with empId & empName property with setter and getters. Following are the Files we will create:

  • pom.xml – because it is a maven project.
  • Employee.java
  • EmpConfig.java- because we are using Java-based configuration.
  • App.java

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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>com.spring.annotation</groupId>
  <artifactId>JavaBasedConfig</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>JavaBasedConfig Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.3.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>JavaBasedConfig</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven 
        defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Employee.java

  • In this file, two properties called empId and empName is created with setters and getters.
  • On-Line no:7, @Value is used to pass the value to the property Id and name.
package com.codedec.java;

import org.springframework.beans.factory.annotation.Value;

public class Employee {

  @Value("105")
  private long empId;
  @Value("Nicolas")
  private String empName;

  public long getEmpId() {
    return empId;
  }

  public void setEmpId(long empId) {
    this.empId = empId;
  }

  public String getEmpName() {
    return empName;
  }

  public void setEmpName(String empName) {
    this.empName = empName;
  }

  public void show() {
    System.out.println("Employee Id: " + empId + "\nEmployee Name: " + empName);
  }
}

EmpConfig

  • Using @Configuration annotation, the container will know that to use this class as a bean Definition.
  • In Short, it is equivalent to XML File “beans.xml” that we used to create.
  • Here, we have to declare a method whose return type should be the name of our POJO class i.e Employee means the name of that bean whose object we have to create and annotate it with @Bean.
package com.codedec.java;

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

@Configuration
public class EmpConfig {

  @Bean
  public Employee getEmployee() {
    return new Employee();
  }
}

App.java

  • In this file, Here we are using the AnnotationConfigApplicationContext class to work with Java Based configuration.
  •  Now, create the Object of Application Context, get the bean from it and call the show() method.
package com.codedec.java;

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

public class App {
  public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(EmpConfig.class);
    Employee employee=context.getBean("getEmployee",Employee.class);
    employee.show();
  }
}

Now, run the App.java File and see the following output

Employee Id: 105
Employee Name: Nicolas

Thus, this was all about – How to use Java-based Configuration using @Configuration & @Bean annotation.