'@ConfigurationProperties on fields

When defining properties with @ConfigurationProperties, can I define the prefix of a specific field instead of the whole class?

For example, let's say we have a Properties class

@ConfigurationProperties(prefix = "com.example")
public class MyProperties {
    private String host;
    private String port;
    // Geters and setters...
}

This will bind the fields host and port to com.example.host and com.example.port. Let's say I want to bind port to com.example.something.port. The way to do this is to define an Inner class Something and add the property port there. But if I need more prefixes it will become too cumbersome. I tried to add @ConfigurationProperties on the setter because the target of the annotation is ElementType.TYPE and ElementType.METHOD:

@ConfigurationProperties(prefix = "com.example.something.port")
public void setPort(int port) {...}

But it did not work in the end. Is there another way to customise the prefix except via Inner classes?



Solution 1:[1]

  1. If you want to map single property, just use @Value annotation.

  2. If you have groups, e.g. like these:

    test1.property1=... test1.test2.property2=... test1.test2.property3=...

You can use

import javax.validation.constraints.NotNull;

import lombok.Getter;
import lombok.Setter;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Getter
@Setter
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(locations = "classpath:myapp.properties")
public class ApplicationProperties {

    private String property1;
    private Test2 test2;

    @Getter
    @Setter
    @ConfigurationProperties(prefix = "test2")
    public static class Test2 {
        @NotNull
        private String property2;
        @NotNull
        private String property3;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1