Nitin Ram Nitin Ram - 5 months ago 25
Java Question

Reading properties file from $TOMCAT_HOME\lib

We have a tiny Web Application using Tomcat server. All the database details are in a properties file as key value pairs for the

hibernate.cfg.xml
to read.


To make it easily managable for the server team, the properties file needs to go to
$TOMCAT_HOME/lib
folder. The Hibernate config file is in:
APP_HOME\src\main\resources\hibernate.cfg.xml



and it can be accessed by the application classes.

The hibernate config file doesn't seem to read
$TOMCAT_HOME/lib/myapp.properties
.

My prime requirement is that the properties file should reside in $TOMCAT_HOME/lib.

Can anyone please suggest me the right thing to do.

Thanks in advance..!

Answer

Thank you V33R and Chetan. Both of your comments had given me a direction. I used the system property

catalina.home

instead of catalina.base which wasn't pointing to the right location I needed. The below is what I finally did:

    private static Properties extractPropertiesFile() throws FileNotFoundException, IOException{

    String propertiesFilePath = System.getProperty("catalina.home") +
            File.separator + "lib"+ File.separator + "myapp.properties";

    Properties properties = new Properties();
    properties.load(new FileInputStream(propertiesFilePath));

    return properties;
}

I had to remove the DB properties which were set in the hibernate.cfg.xml file to the below method. I tried loading the extracted properties file, but was not working as expected and hence loaded them into Hibernate.cfg.Configuration instance as below. To build Session Factory:

 private static SessionFactory buildSessionFactory() {

        try {
            Configuration configuration = new Configuration();
            Properties properties = extractPropertiesFile();

            configuration.configure("hibernate.cfg.xml").setProperties(properties);

            // The properties below are extracted from $TOMCAT_HOME/lib/myapp.properties
            configuration.setProperty("hibernate.connection.driver_class", properties.getProperty("propertyfile.database.driver.classname"));
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()). buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (HibernateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Public Method to get SessionFactory

    public static SessionFactory getSessionFactory() {

    if(sessionFactory == null){
        sessionFactory = buildSessionFactory();
    }
    return sessionFactory;
}
Comments