小编典典

如何从属性文件读取值?

spring

我正在用弹簧。我需要从属性文件中读取值。这是内部属性文件,而不是外部属性文件。属性文件可以如下。

some.properties ---file name. values are below.

abc = abc
def = dsd
ghi = weds
jil = sdd

我需要以传统方式从属性文件中读取这些值。如何实现呢?Spring 3.0是否有最新方法?


阅读 536

收藏
2020-04-11

共1个答案

小编典典

在你的上下文中配置PropertyPlaceholder:

<context:property-placeholder location="classpath*:my.properties"/>

然后,你引用bean中的属性:

@Component
class MyClass {
  @Value("${my.property.name}")
  private String[] myValues;
}

编辑:更新了代码以使用逗号分隔的多个值来解析属性:

my.property.name=aaa,bbb,ccc

如果那不起作用,则可以定义一个带有属性的bean,手动注入和处理它:

<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>
</bean>

and the bean:

@Component
class MyClass {
  @Resource(name="myProperties")
  private Properties myProperties;

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}
2020-04-11