简体   繁体   中英

Spring Boot Configuration Not Working

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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM