Wednesday, July 3, 2024
HomeLanguagesJavaSpring Boot – Auto-configuration

Spring Boot – Auto-configuration

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"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <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.

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments