版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gyshun/article/details/82960363
对于下面的类,使用了@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();
}
}