Customized context.xml per environment using maven

Daniel Cukier picture Daniel Cukier · Jan 19, 2012 · Viewed 7.7k times · Source

I have two context.xml files in my Java web project:

context.xml.development context.xml.production

and I use maven war plugin to build it.

When I build the project, I'd like maven to copy the proper context.xml to the META-INF directory.

How could I do it? I'm already using profiles in my pom.xml

Answer

Tom Chamberlain picture Tom Chamberlain · Aug 26, 2015

Another approach (in case you didn't consider it) is to use one context.xml file with place holders. For example:

<Context>
<Resource name="jdbc/syncDB" auth="Container" type="javax.sql.DataSource"
           maxTotal="100" maxIdle="30" maxWaitMillis="10000"
           username="${database.username}" password="${database.password}" driverClassName="oracle.jdbc.OracleDriver"
           url="${database.url}"/>

</Context>

Then, add the war plugin to your maven pom.xml file that has the META-INF folder as a resource that filters:

    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webResources>
                    <resource>
                        <directory>src/main/webapp/META-INF</directory>
                        <filtering>true</filtering>
                        <targetPath>META-INF</targetPath>
                    </resource>
                </webResources>
            </configuration>
    </plugin>

That way, you can define these placeholder values as defaults that can be overriden for specific profiles:

<properties>
    <database.password>default_user</database.password>
    <database.username>default_password</database.username>
    <database.url>jdbc:oracle:thin:@oracle.host:1521:defaultsid</database.url>
</properties>

<profiles>  
        <profile>   
            <id>dev</id>
            <properties>
                <database.url>jdbc:oracle:thin:@oracle.host:1521:DEVELOPMENTsid</database.url> 
            </properties>
        </profile>
</profiles>