如何从JavaBean(域类)中的属性文件中读取值?

时间:2011-01-19 09:05:09

标签: java spring hibernate jpa

我有一个域类,我想从属性文件中读取值(自动装配messageSource在这里不起作用)所以任何想法? 我正在使用spring,hibernate 这是一个样本:

package com.myapp.domain;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@SuppressWarnings("serial")
@Entity
@Table(name = "domain")
public class MyDomain implements Serializable {

    private long entityId;
    private String domain="some_hardcoded_value" // need to read it from a property file;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    public long getEntityId() {
        return entityId;
    }

    public void setEntityId(long entityId) {
        this.entityId = entityId;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    @Column(name = "domain")
    public String getDomain() {
        return domain;
    }

}

3 个答案:

答案 0 :(得分:3)

我仍然不明白这个问题,但我假设您要从属性文件中设置bean属性。

其他答案显示了如何从.properties文件中获取Properties对象(我将在下面显示其他方法),我将向您展示如何使用Spring的BeanWrapper接口来连接它的属性:

public static void wireBeanFromProperties(Object bean, Properties props){

    BeanWrapper wrapper = new BeanWrapperImpl(bean);
    for(Entry<Object, Object> entry:props.entrySet()){
        String propertyName = entry.getKey().toString();
        if(wrapper.isWritableProperty(propertyName)){
            wrapper.setPropertyValue(propertyName, entry.getValue());
        }
    }

}

或者,如果您确定属性文件中的所有属性都可以映射到该类的bean属性:

public static void wireBeanFromProperties(final Object bean,
    final Properties props){
    final BeanWrapper wrapper = new BeanWrapperImpl(bean);
    // will throw an exception if the Properties object
    // contains any unknown keys
    wrapper.setPropertyValues(props);
}

参考:5.4. Bean manipulation and the BeanWrapper


实际上,从类路径加载资源的特定于Spring的方法使用the Resource mechanism

InputStream str = new ClassPathResource("classpath:some.properties")
                      .getInputStream();

很好的部分是你可以使用classpath:语法轻松地从XML连接InputStreams和Resources:

Java代码

private InputStream stream;
private Resource resource;
public void setStream(InputStream stream){
    this.stream = stream;
}
public void setResource(Resource resource){
    this.resource = resource;
}

物业布线:

<bean class="MyClass">
    <property name="stream" value="classpath:file1.properties" />
    <property name="resource" value="classpath:file2.properties" />
</bean>

如果您只想初始化静态最终字段,请按以下步骤操作:

private static final String DOMAIN;
static{
    InputStream inputStream=null;
    try{
        inputStream = new ClassPathResource("classpath:some.properties")
                          .getInputStream();
        Properties props = new Properties();
        props.load(inputStream);
        String key = "your.property";
        if(!props.containsKey(key))
            throw new IllegalStateException("Property not found");
        DOMAIN= props.getProperty(key);
    } catch(IOException e){
        throw new IllegalStateException(e);
    }finally{
        // apache commons / IO
        IOUtils.closeQuietly(inputStream);
    }
}

答案 1 :(得分:0)

除了一切,你总能做到,

Thread.currentThread.getContextClassLoader().getResourceAsStream("some.properties")

但我仍然很想知道你想在Entity中从属性文件中读到什么。

答案 2 :(得分:0)

添加到安萨里的代码

Properties p = new Properties();
p.load (Thread.currentThread().getContextClassLoader().
         getResourceAsStream("some.properties"));

p.list(System.out);  // or p.get("name")   --> name=value.

在网上搜索后我发现

<!--Bean to load properties file -->  

<bean id="placeholderConfig" 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    
<property name="location" value="classpath:config.properties">  
<!--reads config.properties file-->  

请阅读这篇文章http://www.zparacha.com/how-to-read-properties-file-in-spring/