【问题标题】:How to set propertysource to config file fetched from cloud config server in java spring?java - 如何在java spring中将propertysource设置为从云配置服务器获取的配置文件?
【发布时间】:2019-07-01 20:24:27
【问题描述】:

我正在使用ConfigurationProperties 注释将一些值从 application.yml 映射到 java 类。将它与 localhost 配置文件一起使用时一切正常,但是当我从云配置中获取配置时,找不到这些值。我猜这个问题可能是配置文件名可能会根据选择的配置而有所不同,并且 spring 不知道在哪个文件中查找它们。

@Configuration
@ConfigurationProperties(prefix = "some.prefix")
  public class SomeMappedConfigClass {
    private String variable1;
    private String variable2;
}

和带有配置的 yaml

some.prefix:
  variable1: abc
  variable2: xyz

我试图通过PropertySource 注释映射配置文件,但它期望配置文件名在我的情况下可能不同。

@PropertySource("classpath:some-application.yml")

无论配置文件名如何,有什么方法可以将当前加载的配置传递给 PropertySource? 从云配置成功获取配置后我收到的日志,用于应用程序:web-server profile: LOCAL

Located property source: CompositePropertySource {name='configService', propertySources=[MapPropertySource {name='file:central-config/web-server-LOCAL.yml'}]}

【问题讨论】:

  • 这里没有问题。添加 spring boot 执行器以查看绑定到应用程序的属性。或者检查配置服务器上检索到的属性http://localhost:8888/{application}/{profile}
  • 我验证了它,你是对的,弹簧加载配置正确,我在配置方面遇到了一些问题,谢谢

标签: java spring spring-cloud-config configurationproperties


【解决方案1】:

您可以在类路径中使用外部配置。使用以下传递配置

-Dspring.config.location=your/config/dir/

或者

-Dspring.config.location=classpath:prop1.properties,classpath:prop2.properties

使用下面的代码获取属性值。您可以使用任何一种方法

@Configuration
public class AppConfig {

    @Value("${config.properties:<default values>}")
    String propvalue;

    @Autowired
    Environment env;


    public void method(){
     String datapath = env.getProperty("data.path")
    }

}

【讨论】:

  • 实际上我不想使用@Value,但我阅读了更多关于 spring 环境及其工作原理的信息,我发现 spring 加载配置正确,我在加载配置时遇到了一些问题,谢谢
猜你喜欢
  • 2018-05-15
  • 1970-01-01
  • 2021-03-17
  • 2018-04-14
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
  • 2011-05-07
  • 2017-04-20
相关资源
最近更新 更多