Monday, March 8, 2010

External configuration with Seam



Sometimes you want to load environment-specific configuration properties from a file located in the file system. With Spring this is very easy as all you need to do is to use a property placeholder

<context:property-placeholder location="file:/opt/etc/myprops.properties"/>


Seam does not have an out-of-the-box component to do that but you can write your own

@Name("environment")
@Scope(ScopeType.APPLICATION)
@AutoCreate
public class Environment {
    private Properties properties;

    @Create
    public void setup() {
        try {
            properties = new Properties();
            properties.load(new FileInputStream("/opt/etc/myprops.properties"));
        } catch (IOException e) {
            throw new RuntimeException("Unable to load environment.properties", e);
        }
    }

    public String getProperty(String name) {
        return properties.getProperty(name);
    }
}

Then you can use this component anywhere in your application. For example:

<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://jboss.com/products/seam/components"
            xmlns:core="http://jboss.com/products/seam/core"
            xmlns:async="http://jboss.com/products/seam/async"
            xmlns:transaction="http://jboss.com/products/seam/transaction"
            xmlns:mail="http://jboss.com/products/seam/mail"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation=
                "http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.2.xsd
                 http://jboss.com/products/seam/async http://jboss.com/products/seam/async-2.2.xsd
                 http://jboss.com/products/seam/transaction http://jboss.com/products/seam/transaction-2.2.xsd
                 http://jboss.com/products/seam/mail http://jboss.com/products/seam/mail-2.2.xsd
                 http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.2.xsd">


    <core:init transaction-management-enabled="false"/>

    <transaction:no-transaction/>

    <mail:mail-session session-jndi-name="mail/pdfGeneratorSession"/>


    <component name="ftpHandler">
        <property name="ftpHost">#{environment.getProperty('ftpHost')}</property>
        <property name="ftpPort">#{environment.getProperty('ftpPort')}</property>
        <property name="ftpUser">#{environment.getProperty('ftpUser')}</property>
        <property name="ftpPassw">#{environment.getProperty('ftpPassw')}</property>
    </component>

</components>

No comments:

Post a Comment