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:-

XML




<beans xmlns="http://www.springframework.org/schema/beans"
       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.w3wiki.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:

  • <bean> This element is used to define the bean that will be managed by the Spring IoC Container
  • id is the property assigned to the bean, and this bean will be referred to using this id in the configuration.
  • The <property name> & <value> are key-value pairs that represent that this car has a model as – luxury
  • <property name = “engine” ref = “engine”> defined the dependency that the engine bean has to be injected into the car bean.

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.

Java




//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:

  • The @Configuration annotation is annotated on top of a class which contains bean definition (basically methods that return an instance of a bean), and also the instruction on how to configure the beans and inject dependencies. This annotation lets the Spring framework know that the spring IoC container should process these beans during the initialization of Spring Context.
  • @Bean is used to indicate that this is a Java Bean whose lifecycle will be managed by the Spring IoC Container.
  • In the above code, created two beans – Car and Engine. Also injecting a dependency using a setEngine(engine()) Method manually.

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

Java




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


2. Car Class

Java




//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:

  • Here we’ve used the Spring Constructor injection to inject the Engine dependency in the Car Class. Spring Recommends using Constructor injection over other ways to inject dependencies as our first choice. You can learn more about setter injection and constructor injection here.
  • @Component marks the class as eligible for spring component scanning and provides configuration as soon as the spring boot application launches.
  • Other useful annotation in spring Annotation configuration includes : @Repository, @Service, etc.

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.

Similar Reads

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....

Primary Terminologies

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

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....

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 :...

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....

3. Several ways to configure Spring Boot Application

3.1 Externalized Configuration...

4. Class Path Scanning

...

5. Actuator

...

Advantages Spring Boot Configuration

...

Disadvantages Spring Boot Configuration

...

Conclusion

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....