开发者

How to read values from property file in a JavaBean (domain class)?

开发者 https://www.devze.com 2023-02-05 16:41 出处:网络
I have a domain class and I want to read values from property file (autowiring messageSource w开发者_StackOverflowouldn\'t work here) so any ideas ?

I have a domain class and I want to read values from property file (autowiring messageSource w开发者_StackOverflowouldn't work here) so any ideas ? I am using spring,hibernate and here's a sample:

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;
    }

}


I still don't understand the question, but I'll assume that you want to set bean properties from a properties file.

The other answers have shown how to get a Properties object from a .properties file (I'll show additional ways below), I will show you how to wire properties from it using Spring's BeanWrapper interface:

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());
        }
    }

}

Or, if you know for sure that all properties from the properties file can be mapped to this bean properties of the class:

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);
}

Reference: 5.4. Bean manipulation and the BeanWrapper


Actually, the Spring-specific ways to load resources from the classpath use the Resource mechanism

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

The nice part is that you can wire both InputStreams and Resources easily from XML using the classpath: syntax:

Java Code

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

property wiring:

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

If you just want to initialize a static final field, here's how to do it:

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);
    }
}


Beside everything, you can always do,

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

But I am still curious what you want to read in your Entity, from a property file.


Adding to Ansari's code

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

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

After searching in internet i found below

<!--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-->  

Please read this article http://www.zparacha.com/how-to-read-properties-file-in-spring/

0

精彩评论

暂无评论...
验证码 换一张
取 消