Springboot 中類不能使用@Value註解從yml中載入值
阿新 • • 發佈:2018-11-07
對於下面的類,使用了@Value,但是不能從yml中讀取值,怎麼辦?
帶有@Value標籤類:
package com.itmuch.cloud; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ConfigClientController { @Value("${profile}") private String profile; @GetMapping("/profile") public String getProfile() { return this.profile; } }
需要從下面的yml中提供Profile對應的值,yml如下:
spring:
cloud:
config:
uri: http://localhost:8080
profile: dev
label: master #當ConfigServer後端儲存是GIt的時候,預設是master
application:
name: foobar
解決辦法:
上面的類中加入這個的方法:
@Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }
就可以解決@value直接從yml中讀取資料,不需要寫成@Value("${spring.cloud.config.profile}"),直接寫成@Value("${profile}");
最後上面的類完整的程式碼如下:
package com.itmuch.cloud; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ConfigClientController { @Value("${profile}") private String profile; @GetMapping("/profile") public String getProfile() { return this.profile; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }