Open In App

SpringBoot Configuration

Spring Boot is a powerful framework built on top of the Spring framework. Spring Boot allowed programmers to focus mainly on the business logic without worrying about the external configuration and setting up the environment resources like server setup.

Configuration of SpringBoot

Configuration is the feature of the framework that gives the programmer ease in configuring the application in minimal work and shifts the focus more to the application’s business logic.



In this article, we’ll look into spring boot configuration features and how they help achieve the Convention-over-Configuration (CoC) Principle.

Primary Terminologies

There are some well-known terms often faced while using Springboot as mentioned below:



1. Java Bean

A Java Bean is a terminology defined to refer to the Java objects whose creation, management, and removal when not required anymore (basically the full lifecycle) is managed by the Spring Container.

2. IoC Principle

IoC is an acronym for “Inversion Of Control“. IoC Principle suggests a structured approach for writing development code that is, shifting the creation & management control of Java Beans from the programmer to the framework. This approach allows the programmer to focus more on business logic than deal with the overall lifecycle of trivial Java Beans.

3. Dependency Injection

Dependency Injection (DI) is a core feature of the Spring Boot framework that facilitates the creation & management of Java Beans much organized and easy to implement in the Spring Boot Application.

The Dependencies in the Spring Boot Application are injected through an autonomous procedure performed by the Spring IoC Container at the start of the Spring Boot Application.

4. Annotation

Annotations are the most basic components of the Spring framework that play a crucial role in configuring various aspects of our Spring Boot Application. From creation, management, and management of the lifecycle of certain objects offering a versatile functionality.

In simple words, annotations are a tag that can be put on top of a class, object, or method signifying a specific functionality for that component.

CoC Principle

CoC Principle – Convention Over Configuration is a software development principle that emphasizes boosting developer productivity by minimizing the amount of externalized configuration required to build an application.

This principle work by making certain assumption that can be re-configured by the developer if required. Spring Boot heavily embraces this approach by provisioning support for certain features following are some of them:

Throughout this article, we’ll learn about various technologies that power our Spring Boot application and embrace this principle.

1. Starter File

The starter file is the initial step in configuring a Spring Boot application. You can create your starter file at Spring Initializr specifying the dependencies the version of Java & Spring you want to work with, and the build tool you want to use (maven, gradle, or groove). Then you can download the started file in a zip file format and open it in your favorite IDE. It looks something like this :

Starter File

2. In-Built Server Support

Spring Boot has in-built server support allowing us to embed web servers. This feature allows us to create a stand-alone application, an executable JAR File which is self-contained. By default, Spring Boot uses Tomcat as its default server.

However, if you want to change that you can define an external dependency for the server you want to use in your POM File.

Configuring the server

You can further configure the embedded server, and there are many ways to do this, we’ll see the example of using an external properties file :

# Set Server Port
server.port = 8080
# Set Server Context Path
server.servlet.context-path=/myapp


3. Several ways to configure Spring Boot Application

3.1 Externalized Configuration

Spring boot allows us to configure external database connection (datasource), specific instructions, server configuration, and settings in an external file – either a properties file or yaml file. Both have extensions as – .properties and .yaml

Auto configuration leverages this external file to bind some properties with the bean fields and accommodate them to work as per our specific use case.

application.properties

spring.application.name= ConfigurationApp
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/ConfigDemoDB?autoreconnect=true
server.port=8080
# Custom properties
custom.property1=value1
custom.property2=value2


application.yaml

spring:
  application:
    name: ConfigurationApp
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/ConfigDemoDB?autoreconnect=true
  server:
    port: 8080
# Custom properties
custom:
  property1: value1
  property2: value2


3.2 XML Based Configuration

We can configure our spring boot application using an XML File. XML File contains all the Java Bean definitions and the dependencies that are to be injected. Let’s understand by an example:-

Assume you have a Car & and Engine class as POJOs (Plain old Java objects) to carry data. From a real-world perspective, a car cannot function without an engine. So, here the engine is the dependency to be injected upon the creation of Car Bean. This dependency injection will be taken care of by the Spring IoC Container.

The XML based configuration would look something like this:-




       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">
  
    <!-- Define Engine bean -->
    <bean id="engine" class="com.GeeksforGeeks.Engine">
        <property name="type" value="V-engine" />
    </bean>
  
    <!-- Define Car bean and inject the dependency  -->
    <bean id="car" class="com.example.Car">
        <property name="model" value="luxury" />
        <property name="engine" ref="engine" />
    </bean>
  
</beans>

Explanation of above Code:

Note: XML Configuration is consider legacy and rarely used nowadays.

3.3 Java Based Configuration

Java-based configuration is another modern way to configure our Spring Application, that utilises a specific Java class annotated with @Configuration indication that this class contains the configuration beans, and dependencies that are to be injected upon the launch of the Spring boot application.




//Configuration class for Car-Compoents
  
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
  
@Configuration
public class AppConfig {
      
      // Bean definition - Engine
    @Bean
    public Engine engine() {
        Engine engine = new Engine();
        engine.setType("V-Engine");
        return engine;
    }
    
    // Bean definition - Car
    @Bean
    public Car car() {
        Car car = new Car();
        car.setModel("luxury");
        car.setEngine(engine()); // Dependency injected
        return car;
    }
}

Explanation of above Code:

This code can be optimised to further extents, using Annotation Based Configuration.

3.4 Annotation Based Configuration

Annotation Based Configuration is the most recent way to configure our spring boot application and it is preferred over other configuration types by most modern developers. It minimises the redundant code, improves readability, and promotes the CoC Principle.

1. Engine Class




import org.springframework.stereotype.Component;
  
@Component
class Engine {
    String type;
        
      // Constructor, Getters & Setters
}

2. Car Class




//Java program to denote CAR
  
import org.springframework.stereotype.Component;
  
@Component
class Car {
    String Model;
      Engine engine;
    
      //Constructor Injection
      @Autowired
    public Car(Engine theEngine) 
    
        this.engine = theEngine; 
    
      // Getters & Setters
}

Explanation of above Code:

4. Class Path Scanning

Spring boot employs a feature called classpath scanning (or spring context scanning) that scans through our current project’s directory structure systematically to initialize, inject dependencies and configure beans. This spring scanning offers the programmer a flexibility of only creating and annotating a bean without explicitly specifying to spring where to find it and how to look for it. It is a very productive feature that makes spring boot configuration way easier.

5. Actuator

Spring Boot Actuator is a subproject of Spring Boot, it provides useful insights and an overview of our application by defining a certain set of metrics such as monitoring, healthchecks, logging, and other application-related information. Endpoint examples include :

Note that every endpoint starts from the “actuator” keyword, signifying the same. We can include this sub-project into our application by including the following dependency into our POM File:-




<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Advantages Spring Boot Configuration

Disadvantages Spring Boot Configuration

Conclusion

In conclusion, Spring Boot configuration techniques enhance developer productivity, employing easy configuration and mainly focus on the application’s business logic. Configuration can be done in many ways, there’s no black and whites. Its a matter of personal preferences and your project’s needs.

Spring also offers a very vast documentation support to understand everything in a concise manner.


Article Tags :