tags:

views:

140

answers:

3

Hi All

I have been using spring for a while as my IOC. It has also a very nice way of injecting properties in your beans.

Now I am participating in a new project where the IOC is Guice. I dont understand fully the concept how should I inject properties in to my beans using Guice.

The question : Is it actually possible to inject raw properties ( strings , ints ) into my guice beans. If the answer is no , than maybe you know some nice Properties Framework for java. Because right now I wanted to use the ResourceBundle class for simple properties management in my app. But after using spring for a while this just dont seem seriously enought for me.

+1  A: 

this SO post discusses the use of various configuration frameworks, also the use of properties. I'm not sure it's to the point exactly for your needs, but perhaps you can find something of value there.

Steen
+1  A: 

Injecting properties in Guice is easy. After reading in some properties from a file or however, you bind them using Names.bindProperties(Binder,Properties). You can then inject them using, for example, @Named("some.port") int port.

ColinD
+1  A: 

Spring provides for injection of configuration information found in XML files. I don't want the people installing my software to have to edit XML files, so for the kind of configuration information more properly in a plain text file (such as path information), I've gone back to using java.util.Properties since it's easy to use and fits into Spring pretty well, if you use a ClassPathResource, which permits path-free location of the file itself (it just has to be in the classpath; I put mine at the root of WEB-INF/classes.

Here's a quick method that returns a populated Properties object:

/**
 *  Load the Properties based on the property file specified 
 *  by <tt>filename</tt>, which must exist on the classpath
 *  (e.g., "myapp-config.properties").
 */
public Properties loadPropertiesFromClassPath( String filename )
        throws IOException
{
    Properties properties = new Properties();
    if ( filename != null ) {
        Resource rsrc = new ClassPathResource(filename);
        log.info("loading properties from filename " + rsrc.getFilename() ); 
        InputStream in = rsrc.getInputStream();
        log.info( properties.size() + " properties prior to load" ); 
        properties.load(in);
        log.info( properties.size() + " properties after load" );         
    }
    return properties;
}

The file itself uses the normal "name=value" plaintext format, but if you want to use Properties' XML format just change properties.load(InputStream) to properties.loadFromXML(InputStream). Hope that's of some help.

Ichiro Furusato
I think you missunderstood my question , but thanks for the code and the answer.
Roman