Spring Boot Property Injection

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

Dependencies

dependencies {
    implementation('org.springframework.boot:spring-boot')
}

This declaration assumes we're using Spring Framework Dependency Management System, for Spring Framework-based libraries, or we're building a Spring Boot application.

Injecting Properties into Beans

Property injection is supported by the @ConfigurationProperties annotation. It can be used as shown below.

Configuration Property Holders

A common pattern used to handle injected configuration is to declare a configuration property holder class, whose sole purpose in the application is to be holder of configuration data. Such class bundles several configuration properties together, under a common property namespace. There is nothing special about configuration property holders. They are ordinary Spring components that have their properties injected from the Spring environment. They can be injected into any other bean that needs those properties. One benefit of this approach is that it keeps configuration-specific details out of controllers and other application specific classes. Another benefit is that it makes it easy to share common configuration properties among several beans that may need this information. All configuration properties related to a certain piece of functionality are kept in a single place, as opposite to being scattered across several components, and if we need to add a new property or change an existing property, we do it in a single place.

Configuration property holder classes are a good location to apply JavaBeans Validation annotations.

@Component
@ConfigurationProperties(prefix = "playground.spring.pi")
@Data
@Validated
public class MyPropertyConfiguration {

  public static final int DEFAULT_SIZE = 20;
  public static final String DEFAULT_COLOR = "blue";

  @Min(value = 5, message = "the size must be larger or equal than 5")
  @Max(value = 40, message = "the size must be smaller or equal than 40")
  private int size = DEFAULT_SIZE;
  private String color = DEFAULT_COLOR;
}

Conventionally, hardcoded defaults are specified as initialization values for the member variables.

The property values can then be set externally in a configuration file as follows:

playground:
  spring:
    pi:
      size: 25
      color: "red"

The full playground project is available here:

Playground Property Injection Example

@ConfigurationProperties

This is a Spring Boot annotation, which works by default, without any additional se up, in a Spring Boot environment.

Internally, property files application.properties and/or application.yml are looked for in known locations (classpath:, file:./, classpath:config, file:./config/:) and loaded. The class responsible for doing that is the ConfigFileApplicationListener application event listener.

Exposing Individual Configuration Properties on Components

Individual properties can also be injected directly into established components, as shown:

@Component
@ConfigurationProperties(prefix = "playground.spring.pi")
public class MyComponent {

  public static final int DEFAULT_WEIGHT = 50;

  private int weight = DEFAULT_WEIGHT;

  public void setWeight(int weight) {

    this.weight = weight;
  }
  ...
}

The property values can then be set externally in a configuration file as follows:

playground:
  spring:
    pi:
      weight: 30

However, if you have the option, bundling configuration properties into configuration property holders is generally a better approach, for the reasons presented in that section.

Property Injection and Auto-Configuration

The beans that are automatically configured by the Spring Boot autoconfiguration. process are all configurable by properties drawn from the Spring environment.

Configuration Property Variables

When setting properties, you aren’t limited to declaring their values as string and numeric values. Instead, property values can be derived from from other configuration properties, using the "${...}" (placeholder marker) syntax:

some: 
  attribute: "bright"

playground:
  spring:
    pi:
      color: "${some.attribute} red"

Also see:

Property Placeholders

Configuration Property Metadata

Some IDEs attempt to find metadata about configuration properties, and display a warning around them if such metadata is not found.

Configuration Property Metadata Before.png

Configuration property metadata is completely optional and doesn’t prevent configuration properties from working, but the metadata can be useful for providing some minimal documentation around the configuration properties in the IDE. A way to provide configuration property metadata is to provide a ./src/main/resources/META-INF/additional-spring-configuration-metadata.json file:

{
  "properties": [
    {
      "name": "some.attribute",
      "type": "java.lang.String",
      "description": "this is description for 'some.attribute'."
    },
    {
      "name": "playground.spring.pi.size",
      "type": "java.lang.Integer",
      "description": "this is description for 'playground.spring.pi.size'."
    },
    {
      "name": "playground.spring.pi.color",
      "type": "java.lang.String",
      "description": "this is description for 'playground.spring.pi.color'."
    },
    {
      "name": "playground.spring.pi.weight",
      "type": "java.lang.Integer",
      "description": "this is description for 'playground.spring.pi.weight'."
    }
   ]
}

In IntelliJ IDEA, you will also need to re-run Spring Boot Configuration Annotation Processor to update generated metadata.