【问题标题】:How do i read the application.properties in spring?我如何在春季阅读 application.properties?
【发布时间】:2015-05-23 17:28:08
【问题描述】:

问题与Spring有关。我的项目中有application.properties 文件。我希望在我的服务类中使用这些值。我可以在我的服务类中将这些属性值作为 bean 获取吗?

class MyServiceClass{
    @Autowired
    Properties myproperty;

    // ....
}

我希望能够使用 myproperty。应该对application.properties 与我的服务类进行哪些配置更改?

【问题讨论】:

标签: spring javabeans


【解决方案1】:

您可以将它们注入到您的 bean 中:

 @Value("${name}")
 private String someConfiguration;

【讨论】:

  • 我想要 application.properties 的完整键值对作为 bean。
  • 说,属性 myproperty 应该是自动装配的。
【解决方案2】:

不确定我是否完全理解这个问题。我猜你想从你的 props 文件中访问键和值?如果是这样,也许这会有所帮助:

<bean id="mapProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="fileEncoding" value="UTF-8"/>
    <property name="locations">
        <list>
            <value>classpath:application.properties</value>
        </list>
    </property>
</bean>

<bean id="myMap" class="com.google.common.collect.ImmutableMap" factory-method="copyOf">
    <constructor-arg ref="mapProperties"/>
</bean>

现在您可以像往常一样在 bean 中访问 myMap:

@Autowired
private ImmutableMap<String, String> myMap;

这个例子使用了一个番石榴 ImmutableMap,但你也可以使用 HashMap 或其他什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-18
    • 2015-12-22
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多