Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring Boot - Create a Custom Auto-Configuration
Next article icon

Spring Boot - Create a Custom Auto-Configuration

Last Updated : 08 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
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"?> <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                               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.


Next Article
Spring Boot - Create a Custom Auto-Configuration

P

priyarajtt
Improve
Article Tags :
  • Java
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Create and Configure Topics in Apache Kafka
    Topics are a special and essential component of Apache Kafka that are used to organize events or messages. In other words, Kafka Topics enable simple data transmission and reception across Kafka Servers by acting as Virtual Groups or Logs that store messages and events in a logical sequence. In this
    2 min read
    How to Test Spring Boot Project using ZeroCode?
    Zerocode automated testing framework for a REST API project concept is getting seen via this tutorial by taking a sample spring boot maven project. Let us see the dependencies for Zerocode : <dependency> <groupId>org.jsmart</groupId> <artifactId>zerocode-tdd</artifactId
    5 min read
    Validation in Spring Boot
    In this article, via a Gradle project, let us see how to validate a sample application and show the output in the browser. The application is prepared as of type Spring Boot and in this article let us see how to execute via the command line as well. Example Project Project Structure:   As this is th
    5 min read
    Spring Boot – Validation using Hibernate Validator
    Hibernate Validator provides a powerful and flexible way to validate data in Spring Boot applications. Validating user input is essential for building secure and reliable applications. Spring Boot makes this easy with Hibernate Validator, the reference implementation of JSR 380 (Bean Validation API)
    6 min read
    How to Connect MongoDB with Spring Boot?
    In recent times MongoDB has been the most used database in the software industry. It's easy to use and learn This database stands on top of document databases it provides the scalability and flexibility that you want with the querying and indexing that you need. In this, we will explain how we conne
    4 min read
    Spring Boot - File Handling
    Spring Boot is a popular, open-source spring-based framework used to develop robust web applications and microservices. As it is built on top of Spring Framework it not only has all the features of Spring but also includes certain special features such as auto-configuration, health checks, etc. whic
    5 min read
    Spring Boot MockMVC Testing with Example Project
    In a Spring Boot project, we have to test the web layer. For that, we can use MockMVC. In this tutorial, let us see how to do that by having a sample GeekEmployee bean and writing the business logic as well as the test cases for it. Example Project Project Structure:   This is a maven project. Let's
    5 min read
    Spring Boot Integration With MySQL as a Maven Project
    Spring Boot is trending and it is an extension of the spring framework but it reduces the huge configuration settings that need to be set in a spring framework. In terms of dependencies, it reduces a lot and minimized the dependency add-ons. It extends maximum support to all RDBMS databases like MyS
    4 min read
    Spring Boot Integration With MongoDB as a Maven Project
    MongoDB is a NoSQL database and it is getting used in software industries a lot because there is no strict schema like RDBMS that needs to be observed. It is a document-based model and less hassle in the structure of the collection. In this article let us see how it gets used with SpringBoot as a Ma
    4 min read
    Spring Boot MockMVC Example
    Automated testing plays a vital role in the software industry. In this article, let us see how to do the testing using MockMvc for a Spring Boot project. To test the web layer, we need MockMvc and by using @AutoConfigureMockMvc, we can write tests that will get injected. SpringBootApplication is an
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences