Spring Boot: Load @Value from YAML file

前端 未结 6 1778
一整个雨季
一整个雨季 2020-12-28 14:23

I need to load a property from a .yml file, which contains the path to a folder where the application can read files from.

I\'m using the following code

相关标签:
6条回答
  • 2020-12-28 14:45

    I've got that issue Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder cause I've set test spring boot profile in properties.yaml. Spring can't find properties for test profile when run app with no profile.

    So remove spring boot profile from properties or yaml or run app with enabled profile.

    Configuration file example is below:

    @Configuration
    public class AppConfig {
      @Value("${prop.foo}")
      private String foo;
      @Value("${prop.bar}")
      private String bar;
    
      @Bean
      BeanExample beanExample() {
        return new BeanExample(foo, bar);
      }
    }
    
    0 讨论(0)
  • 2020-12-28 14:47

    I found the above wasn't working for me, because I tried to access the variable in a constructor. But at construction, the value is not injected yet. Eventually I got it to work using this workaround: https://mrhaki.blogspot.com/2015/04/spring-sweets-using-value-for.html

    Maybe this is helpful to others.

    0 讨论(0)
  • 2020-12-28 14:50

    M. Deinum is right, the setup i've provided is working - the yml file was indented wrong, so the property couldn't be found.

    0 讨论(0)
  • 2020-12-28 14:53

    In yml properties file :

    xxxx:
         page:
            rowSize: 1000
    

    Create your Yaml properties config class :

    @Configuration
    @EnableConfigurationProperties
    @ConfigurationProperties(prefix = "xxxx")
    public class YmlPropertiesConfig {
    
        private Page page;
    
        public Page getPage() {
            return page;
        }
        public void setPage(Page page) {
            this.page = page;
        }
    
        public class Page {
            private Integer rowSize;
    
            public Integer getRowSize() {
                return rowSize;
            }
    
            public void setRowSize(Integer rowSize) {
                this.rowSize = rowSize;
            }
        }    
    }
    

    Finally get it and use it :

    public class XXXXController {
    
         @Autowired
         private YmlPropertiesConfig ymlProperties;
    
         public String getIt(){
    
            Integer pageRowSize = ymlProperties.getPage().getRowSize();
         }
    }
    
    0 讨论(0)
  • 2020-12-28 15:02

    For example: application.yml

    key:
     name: description here
    

    Your Class:

    @Value("${key.name}")
    private String abc;
    
    0 讨论(0)
  • 2020-12-28 15:04

    For me a duplicate key in the property file caused this...

    I used same key unknowingly in large yml file.

    key:   
     key1: value
     key2: value
    
    key:  
     key3: value
    
    0 讨论(0)
提交回复
热议问题