Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Externalize Tomcat configuration

Tags:

tomcat

I have a DataSource configuration in context.xml. Is it possible not to hard-code database parameters in that file? For example, use an external properties file, and load the parameters from it?

Something, like this:

context.xml:

  <Resource
  name="jdbc/myDS" auth="Container"
  type="javax.sql.DataSource"
  driverClassName="oracle.jdbc.OracleDriver"
  url="${db.url}"
  username="${db.user}"
  password="${db.pwd}"
  maxActive="2"
  maxIdle="2"
  maxWait="-1"/>

db.properties:

db.url=jdbc:oracle:thin:@server:1521:sid
db.user=test
db.pwd=test
like image 982
never Avatar asked Jul 13 '12 10:07

never


Video Answer


1 Answers

As stated here, you could do this in the following way.

1.Download tomcat library to get the interface definition, for instance by defining maven dependency:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-coyote</artifactId>
        <version>7.0.47</version>
    </dependency>

2.Next step is to create a com.mycompany.MyPropertyDecoder in the following way:

import org.apache.tomcat.util.IntrospectionUtils;
public class MyPropertyDecoder implements IntrospectionUtils.PropertySource  {
    @Override
    public String getProperty(String arg0) {
        //TODO read properties here
        return null;
    }
}

3.Put MyPropertyDecoder.class into tomcat7/lib folder
4.Define org.apache.tomcat.util.digester. PROPERTY_SOURCE property at tomcat7/conf/catalina.properties as following:

org.apache.tomcat.util.digester.PROPERTY_SOURCE=com.mycompany.MyPropertyDecoder

5.Update your context.xml with properties vars

<Resource name="jdbc/TestDB"
           auth="Container"
           type="javax.sql.DataSource"
           username="root"
           password="${db.password}"
           driverClassName="com.mysql.jdbc.Driver"
           url="jdbc:mysql://localhost:3306/mysql?autoReconnect=true"
           ...  

6.Put application.properties file somewhere in your project/container
7.Make sure MyPropertyDecoder correctly reads application.properties
8.Enjoy!

PS Also there is a similar approach described for tc Server.

like image 192
Anton Shchastnyi Avatar answered Sep 28 '22 06:09

Anton Shchastnyi