Spring-boot: set default value to configurable properties

后端 未结 2 1514
无人共我
无人共我 2021-02-18 18:24

I have a properties class below in my spring-boot project.

@Component
@ConfigurationProperties(prefix = \"myprefix\")
public class MyProperties {
    private Str         


        
相关标签:
2条回答
  • 2021-02-18 18:48

    Check if property1 was set using a @PostContruct in your MyProperties class. If it wasn't you can assign it to another property.

    @PostConstruct
        public void init() {
            if(property1==null) {
                property1 = //whatever you want
            }
        }
    
    0 讨论(0)
  • 2021-02-18 18:50

    In spring-boot 1.5.10 (and possibly earlier) setting a default value works as-per your suggested way. Example:

    @Component
    @ConfigurationProperties(prefix = "myprefix")
    public class MyProperties {
    
      @Value("${spring.application.name}")
      protected String appName;
    }
    

    The @Value default is only used if not overridden in your own property file.

    0 讨论(0)
提交回复
热议问题