4
votes

I'm using Spring boot.

I have an application.yml in src/main/resources. I then have a Configuration class that I am trying to get to load the application.yml. However, when I try to use the configuration class in another bean, the values are null. See the ApiHelper.java as to where the values are null.

I'm attempting to run the jar as so:

java -jar build/libs/app.jar

Am I doing something wrong? I've also tried using a properties file instead. When I unzip the jar file the configuration files are in the root.

src/main/resources/application.yml

spring: 
    profiles.active: default
---
spring:
   profiles: default
api:
   path: http://some-path
---
spring:
   profiles: qa
api:
   path: http://some-path2

src/main/java/AppConfig.java

@Configuration
@EnableConfigurationProperties(ApiConfig.class)
public class AppConfig {
    @Autowired
    private ApiConfig apiConfig;

    @ConfigurationProperties(value = "api", exceptionIfInvalid=true)
    public static class ApiConfig {
        private String path;

        public ApiConfig() {
            System.out.println("Am I getting called?");  // yes it is
        }

        public String getPath() {
            return path;
        }
    }

    @Bean
    public ApiHelper getApiHelper() {
        return new ApiHelper();
    }
}

src/main/java/ApiHelper.java

public class ApiHelper {
    @Autowired
    private ApiConfig apiConfig;

    @PostConstruct
    private void init() {
        System.out.println(apiConfig); // prints ApiConfig@168498d6
        System.out.println(apiConfig.getPath()); // prints null
    }
}
1

1 Answers

2
votes

It turns out that you need a setter to make it work:

@ConfigurationProperties(value = "api", exceptionIfInvalid=true)
public static class ApiConfig {
    ...
    public void setPath(String path) {
        this.path = path;
    }
}