【问题标题】:Spring load specific properties into a properties objectSpring 将特定属性加载到属性对象中
【发布时间】:2018-04-17 16:34:25
【问题描述】:

我的application.properties包含以下属性:

db.username = ...
db.password = ...
db.timeout = ...

rest.client.username = ...
rest.client.password = ...
rest.client.timeout = ...

我只想将其余客户端的属性加载到配置中

@Configuration
public class Config {

....

private Properties restProperties; // << here should go 3 properties with prefix rest.client

}

有什么方法可以在基于 Java 的配置中做到这一点?

【问题讨论】:

    标签: spring properties


    【解决方案1】:

    如果您将所有rest.client 属性移动到它们自己的属性文件中(例如restclient.properies),您可以使用PropertiesLoaderUtils

    Resource resource = new ClassPathResource("/restclient.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    

    或者,您可以使用@ConfigurationProperties,如here 所示,但它不是Properties 对象,而是您自己定义的对象。

    另外,我觉得值得一提的是你可以添加

    @Autowired
    private Environment env;
    

    并通过使用访问任何属性

    env.getProperty("your.property.here")
    

    【讨论】:

      猜你喜欢
      • 2011-10-03
      • 2013-01-20
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多