Search code examples
mavenjakarta-eeproperties-file

Best way to extract DataBase connection settings to external file in Java EE Maven project


On my local machine I am creating Java EE Maven project on Tomcat7 that collaborates with local MySQL database.

For now I have all db connection settings like (user, password, host, dbname, ... etc) hardcoded in DatabaseQueries.java directly in Java EE Maven project, but I know it is not right and I want to take out this setting from project for example to db.properties file, so when I deploy the project on my remote Tomcat7 server it will use different db.properties file with corresponing settings or if I share the project in GitHub, other people will not see my db username and password.

Thus I have few questions:

  1. What is the best practice of externalizing the db settings from Maven project ?

  2. Does Maven project has already build-in functionality to do this ?

  3. How to be sure, that when I export a project as a *.WAR file it will not include this db.properties file ?

  4. Is it correct to use the name as "db.properties" for this purposes ?


Solution

  • For example , in your project add 4 folders :

    1. Your Project\src\main\resources\

      \local > db.properties
      \integration > db.properties
      \deploy > db.properties
      \Default > db.properties
      
    2. in pom.xml add :

       <properties>
           <param>Default</param>
       </properties>
      

      and

       <build>
           <resources>
               <resource>
                   <directory>src/main/resources/${param}</directory>           
               </resource>
           </resources>
       </build> 
      
       if : mvn clean install   : classpath => db.properties(from Default)
      
       if : mvn clean install -Dparam=local : classpath => db.properties(from local)
      
       if : mvn clean install -Dparam=integration : classpath => db.properties(from integration)
      
       if : mvn clean install -Dparam=deploy : classpath => db.properties(from deploy)
      

    Much better than using profiles is more extensible without touching the pom.