Search code examples
javaspringspring-bootapache-commons-config

create a commons config Configuration object from standard Properties object


I am loading settings from a YAML file and having Spring autowire the results in a Properties bean like so:

@ConfigurationProperties(prefix = "myPrefix")
@Bean
private Properties getProperties() {
    return new Properties();
}

However, the Properties class is rather limiting, and I would like to have an Apache commons config Configuration object. The commons config documentation says that it can be integrated with Spring, but I don't see an example for this simple use case.

How can I autowire an apache commons Configuration in Spring Boot?


Solution

  • I do not think there is any ready-made solution for getting an Apache Commons Configuration object. However, you can get Spring's Environment object, which implements PropertyResolver, which is much more advanced than Properties (you can retrieve properties of any class type). You can get it autowired in your application's constructor like so:

    ...
    private final Environment env;
    @Autowired
    public MyApplication(Environment env) {
        this.environment = env;
    }
    ...