如何从属性文件中读取值?

use*_*403 122 spring properties-file

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

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

abc = abc
def = dsd
ghi = weds
jil = sdd
Run Code Online (Sandbox Code Playgroud)

我需要以传统方式从属性文件中读取这些值.怎么实现呢?有没有关于spring 3.0的最新方法?

mre*_*isz 188

在您的上下文中配置PropertyPlaceholder:

<context:property-placeholder location="classpath*:my.properties"/>
Run Code Online (Sandbox Code Playgroud)

然后你引用bean中的属性:

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

编辑:更新代码以使用mutliple逗号分隔值解析属性:

my.property.name=aaa,bbb,ccc
Run Code Online (Sandbox Code Playgroud)

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

<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

和豆:

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

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于处理逗号分隔值的情况,可以考虑使用EL来提出这里提出的建议:http://stackoverflow.com/questions/12576156/reading-a-list-from-properties-file-and-load-与弹簧的注释值 (2认同)
  • 我们如何使用`aaa`?它是`@Value($ {aaa})private String aaa;`那么我们可以`System.out.println(aaa)`??????? (2认同)
  • @ user75782131更准确地说`@Value("$ {aaa}")`,请注意引号.是的,您可以打印它,除非在构造函数中,因为构造函数在注入值之前执行. (2认同)

mok*_*ino 42

在配置类中

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
   @Autowired
   Environment env;

   @Bean
   public TestBean testBean() {
       TestBean testBean = new TestBean();
       testBean.setName(env.getProperty("testbean.name"));
       return testBean;
   }
}
Run Code Online (Sandbox Code Playgroud)


小智 41

有各种方法可以实现同样的目标.以下是春季常用的一些方法 -

  1. 使用PropertyPlaceholderConfigurer
  2. 使用PropertySource
  3. 使用ResourceBundleMessageSource
  4. 使用PropertiesFactoryBean

    还有很多........................

假设ds.type您的属性文件中有关键字.


运用 PropertyPlaceholderConfigurer

注册PropertyPlaceholderConfigurerbean-

<context:property-placeholder location="classpath:path/filename.properties"/>
Run Code Online (Sandbox Code Playgroud)

要么

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:path/filename.properties" ></property>
</bean>
Run Code Online (Sandbox Code Playgroud)

要么

@Configuration
public class SampleConfig {
 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
  //set locations as well.
 }
}
Run Code Online (Sandbox Code Playgroud)

注册后PropertySourcesPlaceholderConfigurer,您可以访问价值 -

@Value("${ds.type}")private String attr; 
Run Code Online (Sandbox Code Playgroud)

运用 PropertySource

在最新版本的春天,你不需要注册PropertyPlaceHolderConfigurer使用@PropertySource,我发现了一个很好的链接,了解版本兼容性-

@PropertySource("classpath:path/filename.properties")
@Component
public class BeanTester {
    @Autowired Environment environment; 
    public void execute() {
        String attr = this.environment.getProperty("ds.type");
    }
}
Run Code Online (Sandbox Code Playgroud)

运用 ResourceBundleMessageSource

注册Bean-

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
    <list>
      <value>classpath:path/filename.properties</value>
    </list>
  </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

访问价值 -

((ApplicationContext)context).getMessage("ds.type", null, null);
Run Code Online (Sandbox Code Playgroud)

要么

@Component
public class BeanTester {
    @Autowired MessageSource messageSource; 
    public void execute() {
        String attr = this.messageSource.getMessage("ds.type", null, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

运用 PropertiesFactoryBean

注册Bean-

<bean id="properties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath:path/filename.properties</value>
    </list>
  </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

Wire Properties实例进入您的班级 -

@Component
public class BeanTester {
    @Autowired Properties properties; 
    public void execute() {
        String attr = properties.getProperty("ds.type");
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*urt 25

这是一个额外的答案,对我理解它是如何工作也很有帮助:http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

必须使用静态修饰符声明任何BeanFactoryPostProcessor bean

@Configuration
@PropertySource("classpath:root/test.props")
public class SampleConfig {
 @Value("${test.prop}")
 private String attr;
 @Bean
 public SampleService sampleService() {
  return new SampleService(attr);
 }

 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ohn 9

如果需要在不使用@Value的情况下手动读取属性文件.

感谢Lokesh Gupta精心编写的页面:博客

在此输入图像描述

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;


public class Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());

    public static Properties fetchProperties(){
        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return properties;
    }
}
Run Code Online (Sandbox Code Playgroud)


Mil*_*una 7

另一种方法是使用ResourceBundle。基本上你使用它的名字来获得包,而没有“.properties”

private static final ResourceBundle resource = ResourceBundle.getBundle("config");
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方法恢复任何值:

private final String prop = resource.getString("propName");
Run Code Online (Sandbox Code Playgroud)


ins*_*ect 6

您需要在应用程序上下文中放置PropertyPlaceholderConfigurer bean并设置其location属性.

详情请见:http://www.zparacha.com/how-to-read-properties-file-in-spring/

您可能需要稍微修改属性文件才能使此工作正常.

希望能帮助到你.