Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Springboot @ConfigurationProperties nested yaml properties don't load

For some reason non-nested properties load but nested don't.

Configuration:

spring:
  profile: junit
  profiles:
    include: base

Config class:

@ConfigurationProperties(prefix = "spring")
public class MyFirstProperties {

    private String profile;
    private Profiles profiles;
    // getters and setters


    public class Profiles
    {
        private String include;
    // getters and setters
    }
}

Main class:

    @SpringBootApplication
    @EnableConfigurationProperties(MyFirstProperties.class)
    public class Main {
        public static void main(String... args) {
            SpringApplication.run(Main.class, args);
        }
}

When I inject configuration class to my controller and call getter for a non-nested property it returns its value. But a getter for a nested property returns null.

Annotating inner class with ConfigurationProperties and its own prefix does not seem to work. Am I missing something?

like image 511
Iwavenice Avatar asked Mar 18 '19 17:03

Iwavenice


People also ask

How can we access the YAML properties in Spring boot?

To access the YAML properties, we'll create an object of the YAMLConfig class, and access the properties using that object. In the properties file, we'll set the spring. profiles. active environment variable to prod.

How do you call a properties file in Spring boot?

Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.

How do you define properties in Spring boot?

We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name. For example, if we define a “staging” environment, that means we'll have to define a staging profile and then application-staging. properties.


1 Answers

You need to instantiate your profiles property

private Profiles profiles = new Profiles();

That's it.

This happens because your inner class isn't static.
You cannot instantiate this type of class directly, but only inside the context of the enclosing one.

Make your class static and you'll be good to go

public static class Profiles { ... }
like image 104
LppEdd Avatar answered Oct 06 '22 00:10

LppEdd