如何从属性文件中读取值? [英] How to read values from properties file?

查看:146
本文介绍了如何从属性文件中读取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using spring. I need to read values from properties file. This is internal properties file not the external properties file. Properties file can be as below.

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

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

我需要以传统方式从属性文件中读取这些值.如何实现呢? Spring 3.0有什么最新的方法吗?

I need to read those values from the properties file not in traditional way. How to achieve it? Is there any latest approach with spring 3.0?

推荐答案

在您的上下文中配置PropertyPlaceholder:

Configure PropertyPlaceholder in your context:

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

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

Then you refer to the properties in your beans:

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

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

updated the code to parse property with mutliple comma-separated values:

my.property.name=aaa,bbb,ccc

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

If that doesnt work, you can define a bean with properties, inject and process it manually:

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

和豆子:

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

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

这篇关于如何从属性文件中读取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆