Kre4
Kre4

Reputation: 95

Use different prefixes in spring boot @Configuration/@ConfigurationProperties

I have spring boot app, and .yaml file with such configuration:

storage:
  path: C:\\path\\example
cache:
  durtion: 60

I need ONE class, that will contain both cache and storage. I thought that @ConfigurationProperties will help me, but the only thing I can do with this annotation is creating two different classes:

@Component
@ConfigurationProperties(prefix = "storage")
public class ConfigA(){
     @Getter
     @Setter
     private String path;
}
...

@Component
@ConfigurationProperties(prefix = "cache")
public class ConfigB(){
     @Getter
     @Setter
     private int duration;
}

How can I combine ConfigA and ConfigB in one class? Is it possible to it without using @Value? Update: I've managed to do something like this, but I'm not sure this is the best way:

@Configuration
public class ValuesConfig {

    @Bean
    @ConfigurationProperties(prefix = "cache")
    public Cache cache(){
        return new Cache();
    }

    @Component
    public static class Cache{
        @Getter
        @Setter
        private int duration;
    }

}

Upvotes: 1

Views: 1832

Answers (1)

cerdoc
cerdoc

Reputation: 515

You can have a 'global' config with no prefix, SpringBoot will try to fulfil it from the 'root' of all the properties


public class StorageConfig(){
     @Getter
     @Setter
     private String path;
}

public class CacheConfig(){
     @Getter
     @Setter
     private int duration;
}

@Component
@ConfigurationProperties
public class GlobalConfig(){
     @Getter
     @Setter
     private StorageConfig storage;
     @Getter
     @Setter
     private CacheConfig cache;
}

As you annotate your configs with @Component they are injectable as any other component so you just have to inject to access the properties they hold.

Upvotes: 1

Related Questions