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 - Auto-configuration
Next article icon

Spring Boot - Auto-configuration

Last Updated : 11 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring Boot is heavily attracting developers toward it because of three main features as follows:

  1. Auto-configuration - such as checking for the dependencies, the presence of certain classes in the classpath, the existence of a bean, or the activation of some property.
  2. An opinionated approach to configuration.
  3. The ability to create stand-alone applications.

Auto-Configuration in Spring Boot

  • @Conditional annotation acts as a base for the Spring Boot auto-configuration annotation extensions.
  • It automatically registers the beans with @Component, @Configuration, @Bean, and meta-annotations for building custom stereotype annotations, etc.
  • The annotation @EnableAutoConfiguration is used to enable the auto-configuration feature.
  • The @EnableAutoConfiguration annotation enables the auto-configuration of Spring ApplicationContext by scanning the classpath components and registering the beans.
  • This annotation is wrapped inside the @SpringBootApplication annotation along with @ComponentScan and @SpringBootConfiguration annotations.
  • When running main() method, this annotation initiates auto-configuration.

Implementation: Bootstrapping of Application

Java
// Java Program to Illustrate Bootstrapping of Application  package gfg;  // Importing required classes import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  // Annotation @SpringBootApplication  // Class public class GfgApplication {      // Main driver method     public static void main(String[] args)     {         SpringApplication.run(GfgApplication.class, args);     } } 

Note: You should use the '@EnableAutoConfiguration' annotation only one time in your application.

  • 'spring-boot-autoconfigure.jar' is the file that looks after all the auto-configuration.
  • All auto-configuration logic for MVC, data, JMS, and other frameworks is present in a single jar

Working of Auto-Configuration in Spring Boot 

A: Dependencies

  • Auto-Configuration is the main focus of the Spring Boot development.
  • Our Spring application needs a respective set of dependencies to work.
  • Spring Boot auto-configures a pre-set of the required dependencies without a need to configure them manually.
  • This greatly helps and can be seen when we want to create a stand-alone application.
  • When we build our application, Spring Boot looks after our dependencies and configures both the underlying Spring Framework and required jar dependencies (third-party libraries ) on the classpath according to our project built.
  • It helps us to avoid errors like mismatches or incompatible versions of different libraries.
  • If you want to override these defaults, you can override them after initialization.

Tool: Maven

Example 1: 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.5.6</version>         <relativePath/> <!-- lookup parent from repository -->     </parent>     <groupId>sia</groupId>     <artifactId>taco-cloud</artifactId>     <version>0.0.1-SNAPSHOT</version>     <name>taco-cloud</name>     <description>Demo project for Spring Boot</description>     <properties>         <java.version>11</java.version>         <vaadin.version>14.7.5</vaadin.version>     </properties>     <dependencies>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-thymeleaf</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>         </dependency>          <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-devtools</artifactId>             <scope>runtime</scope>             <optional>true</optional>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-test</artifactId>             <scope>test</scope>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-jersey</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web-services</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-webflux</artifactId>         </dependency>         <dependency>             <groupId>com.vaadin</groupId>             <artifactId>vaadin-spring-boot-starter</artifactId>         </dependency>         <dependency>             <groupId>io.projectreactor</groupId>             <artifactId>reactor-test</artifactId>             <scope>test</scope>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter</artifactId>         </dependency>         <dependency>             <groupId>org.projectlombok</groupId>             <artifactId>lombok</artifactId>             <optional>true</optional>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-data-jdbc</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-jdbc</artifactId>         </dependency>         <dependency>             <groupId>com.h2database</groupId>             <artifactId>h2</artifactId>             <scope>runtime</scope>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-data-jpa</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-security</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.security</groupId>             <artifactId>spring-security-test</artifactId>             <scope>test</scope>         </dependency>         <dependency>             <groupId>mysql</groupId>             <artifactId>mysql-connector-java</artifactId>             <scope>runtime</scope>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-hateoas</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-data-rest</artifactId>         </dependency>     </dependencies>      <build>         <plugins>             <plugin>                 <groupId>org.springframework.boot</groupId>                 <artifactId>spring-boot-maven-plugin</artifactId>                 <configuration>                     <excludes>                         <exclude>                             <groupId>org.projectlombok</groupId>                             <artifactId>lombok</artifactId>                         </exclude>                     </excludes>                 </configuration>             </plugin>         </plugins>     </build>      <dependencyManagement>         <dependencies>             <dependency>                 <groupId>com.vaadin</groupId>                 <artifactId>vaadin-bom</artifactId>                 <version>${vaadin.version}</version>                 <type>pom</type>                 <scope>import</scope>             </dependency>         </dependencies>     </dependencyManagement>     <profiles>         <profile>             <id>production</id>             <build>                 <plugins>                     <plugin>                         <groupId>com.vaadin</groupId>                         <artifactId>vaadin-maven-plugin</artifactId>                         <version>${vaadin.version}</version>                         <executions>                             <execution>                                 <id>frontend</id>                                 <phase>compile</phase>                                 <goals>                                     <goal>prepare-frontend</goal>                                     <goal>build-frontend</goal>                                 </goals>                                 <configuration>                                     <productionMode>true</productionMode>                                 </configuration>                             </execution>                         </executions>                     </plugin>                 </plugins>             </build>         </profile>     </profiles> </project> 

Understanding Auto-Configuration of Dependencies

  • When you build a Spring Boot project, the 'Starter Parent' dependency gets automatically added in the 'pom.xml' file.
  • It notifies that the essential 'sensible' defaults for the application have been auto-configured and you therefore can take advantage of it.
<parent>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-parent</artifactId>  <version>...</version>  </parent>
  • To add the dependency ( library of tech stacks ), you don't need to mention the version of it because the Spring Boot automatically configures it for you.
  • Also, when you update/change the Spring Boot version, all the versions of added dependencies will also get updated/changed.
<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-thymeleaf</artifactId>  </dependency>
  • It is Spring Boot's auto-configuration that makes managing dependencies supremely easy for us.
  • With the help of enabling 'debug logging' in the 'application.properties' file, we can know more about auto-configuration.
logging.level.org.springframework: DEBUG  

Tool B: Gradle

Example 2: build.gradle

buildscript {     repositories {         jcenter()     }       dependencies {         classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.8.RELEASE")     }  }    apply plugin: 'java'  apply plugin: 'spring-boot'    repositories {     jcenter()  }    dependencies {     compile("org.springframework.boot:spring-boot-starter-web")     testCompile("org.springframework.boot:spring-boot-starter-test")  }

B: Spring Application

Illustration: Class   

  1. @Bean is a method-level annotation.
  2. @Bean annotation specifies that a method produces a return value registered as a bean ( data ) with BeanFactory - managed by Spring Container.
  3. This particular java program uses @Configuration annotation specifying that the class contains one or more @Bean annotations which help to automatically register (initialize) in the Spring Container (Spring Application Context).
  4. @Configuration is a class-level annotation.

Example

Java
// Java Program Illustrating Configuration of // DataSourceConfiguration of DataSource  package gfg;  // Importing required classes import javax.sql.DataSource; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;  // Annotation @Configuration  // Class public class ConfigDataSource {      // Annotation     @Bean public static DataSource source()     {          DataSourceBuilder<?> dSB             = DataSourceBuilder.create();         dSB.driverClassName("com.mysql.jdbc.Driver");          // MySQL specific url with database name         dSB.url("jdbc:mysql://localhost:3306/userdetails");          // MySQL username credential         dSB.username("user");          // MySQL password credential         dSB.password("password");          // builds and returns a new         // configured datasource object         return dSB.build();     } } 

Note: Java Spring Boot framework's auto configuration feature enables you to start developing your Spring-based applications fast and reduces the possibility of human errors.


Next Article
Spring Boot - Auto-configuration

P

pawardarshan461
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    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
    Spring Boot Integration With PostgreSQL as a Maven Project
    PostgreSQL is a user-friendly versatile RDBMS. This article lets us see how to integrate Spring Data JPA with PostgreSQL. There are some conventions to be followed while using PostgreSQL. We will cover that also. Working with PostgreSQL We can easily create databases and tables in that. The below sc
    3 min read
    Spring Boot JPA Sample Maven Project With Query Methods
    In this article, let us see a sample maven project in Spring Boot JPA with Query methods. Spring Boot + JPA removes the boilerplate code and it will be enhanced much if we use query methods as well. Let us discuss this project with MySQL Connectivity for geeksforgeeks database and table name as "Con
    6 min read
    Spring Boot - Service Class Example for Displaying Response Codes and Custom Error Codes
    Sometimes the error or status messages in webpages would be different from the default error message thrown by Tomcat (or any other server). An important reason for this is websites want to look unique in their approach to their users. So, a customized page for displaying status codes is always bett
    6 min read
    Spring Boot - Create a Custom Auto-Configuration
    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 th
    4 min read
    Spring Boot - Consume Message Through Kafka, Save into ElasticSearch, and Plot into Grafana
    In this article, we are going to make a program to produce some data using Kafka Producer which will consume by the Kafka Consumer and save into the elastic search DB, and later on, plot that JSON data into the Grafana dashboard. Start with configuring all the required software and tool. Requirement
    7 min read
    How to Implement AOP in Spring Boot Application?
    AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of
    10 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