Open In App

Spring Boot – Create a Custom Auto-Configuration

Last Updated : 08 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Usually, we might be taking a maven project or grade project for Spring Boot related projects. We will be adding the dependencies in pom.xml (in case of a maven project). In a spring application, Spring Boot auto-configuration helps to automatically configure by checking with the jar dependencies that we have added. For example, though no beans are specifically given for beans related to the database because of the existence of database jar/database dependency in pom.xml, Spring Boot’s auto-configuration feature automatically configures it in the project.

@SpringBootApplication = @ComponentScan + @EnableAutoConfiguration + @Configuration

Hence the code that has @SpringBootApplication will take care of doing the auto-configuration automatically. No need to worry about using the annotation @EnableAutoConfiguration. 

spring-boot-starter-web dependency

If this dependency is provided, it looks for the Spring MVC (Model View Controller) in the classpath. It also auto-configures DispatcherServlet and additionally web jars that are required to do MVC functionally and a default error is all set.

spring-boot-starter-data-jpa dependency

Automatically it configures a data source and an Entity Manager. Let us see Spring Boot Auto Configuration via an example project

Example Project

Project Structure: 

Project Structure

 

This is the maven-driven project

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.2.2.RELEASE</version>
      <relativePath />
   </parent>
   <groupId>com.javatpoint</groupId>
   <artifactId>spring-boot-autoconfiguration-example</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>spring-boot-autoconfiguration-example</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>1.8</java.version>
   </properties>
   <dependencies>
      <!-- Need to specify the dependencies for spring boot project -->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.apache.tomcat</groupId>
         <artifactId>tomcat-jasper</artifactId>
         <version>9.0.30</version>
      </dependency>
      <dependency>
         <groupId>com.h2database</groupId>
         <artifactId>h2</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
         <exclusions>
            <exclusion>
               <groupId>org.junit.vintage</groupId>
               <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
         </exclusions>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>


Let us see the important files in the project

IllustrationOfSpringBootAutoconfigurationExampleApplication.java

Java




import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
  
// @SpringBootApplication=@ComponentScan+@EnableAutoConfiguration+@Configuration
@SpringBootApplication
public class IllustrationOfSpringBootAutoconfigurationExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(IllustrationOfSpringBootAutoconfigurationExampleApplication.class, args);
    }
}


Let us see the controller file

SampleControllerDemo.java

Java




import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
  
@Controller
public class SampleControllerDemo {
    @RequestMapping("/")
    public String home() {
        return "homePage.jsp";
    }
}


GeekUser.java

Java




import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
  
@Entity
// This table will be created and we can view the data
// as we are inserting the data in the sql
@Table(name = "geekuserdata")
public class GeekUser {
    @Id private int id;
    private String username;
    
    private String noOfPosts;
    private String proficiencies;
  
    public String getUsername() { return username; }
  
    public void setUsername(String username)
    {
        this.username = username;
    }
  
    public String getNoOfPosts() { return noOfPosts; }
  
    public void setNoOfPosts(String noOfPosts)
    {
        this.noOfPosts = noOfPosts;
    }
  
    public String getProficiencies()
    {
        return proficiencies;
    }
  
    public void setProficiencies(String proficiencies)
    {
        this.proficiencies = proficiencies;
    }
  
    public int getId() { return id; }
  
    public void setId(int id) { this.id = id; }
  
    public String getUname() { return username; }
  
    public void setUname(String username)
    {
        this.username = username;
    }
  
    @Override public String toString()
    {
        return "GeekUser [id=" + id + ", uname=" + username
            + ", noOfPosts = " + noOfPosts
            + ", proficiencies= " + proficiencies + "]";
    }
}


src/main/resources/data.sql

insert into geekuserdata values(1,'Rachel','100','Java');
insert into geekuserdata values(2,'Monica','75','Python');
insert into geekuserdata values(3,'Phoebe','70','PHP');

src/main/resources/application.properties

server.port=8085 // That means the server port
spring.h2.console.enabled=true
spring.datasource.plateform=h2 //h2 is used
spring.datasource.url=jdbc:h2:mem:gfg // jdbc:h2:mem:gfg is going to get used
logging.level.org.springframework: DEBUG // With this we can see in output all the potential matches

Let us create a web page called homePage.jsp 

src/main/webapp/homePage.jsp

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
   <head>
      <meta charset="ISO-8859-1">
      <title>Demo for Spring Boot Autoconfiguration</title>
   </head>
   <body>
      <div align="center">
         <h1>Add Geek Users</h1>
         <form action="<%=request.getContextPath()%>/addUser" method="post">
            <table style="with: 100%">
               <tr>
                  <td>ID</td>
                  <td><input type="text" name="id" /></td>
               </tr>
               <tr>
                  <td>User Name</td>
                  <td><input type="text" name="userName" /></td>
               </tr>
            </table>
            <input type="submit" value="Submit" />
         </form>
      </div>
   </body>
</html>


Run the file ‘IllustrationOfSpringBootAutoconfigurationExampleApplication’ now. In the console, we can see this output

Output Console

 

In the application.properties, if we have enabled

logging.level.org.springframework: DEBUG

we can see these additional outputs in the console

Output Console

 

Output Console

 

On hitting http://localhost:8085/, we can see the below output, which is nothing but the given JSP page (homePage.jsp)

Output

 

Similarly on hitting http://localhost:8085/h2-console/

Output

 

Output

 

In the console, if we carefully observe we can see that TransactionManagement, EntityManagerFactory, and DataSource are automatically configured, as shown in the following figure.

Output Console

 

So once the dependencies are given, Spring boot automatically configures everything.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads