在 Java EE Maven 项目中将数据库连接设置提取到外部文件的最佳方法

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

在我的本地计算机上,我正在 Tomcat7 上创建 Java EE Maven 项目,该项目与本地 MySQL 数据库协作。

现在我已经在 Java EE Maven 项目中直接在 DatabaseQueries.java 中硬编码了所有数据库连接设置,如(用户、密码、主机、数据库名称等),但我知道是不对的,我想从项目中取出这个设置,例如 db.properties 文件,所以当我在我的远程 Tomcat7 服务器上部署项目时,它将使用不同的 db.properties 具有相应设置的文件,或者如果我在 GitHub 中共享项目,其他人将看不到我的数据库用户名和密码。

所以我有几个问题:

  1. 从外部化数据库设置的最佳实践是什么 Maven 项目 ?

  2. Maven 项目是否已经内置了执行此操作的功能?

  3. 当我将项目导出为 *.WAR 文件时如何确定 它不会包含此 db.properties 文件 ?

  4. 为了这个目的使用名字 "db.properties" 是否正确?

例如,在您的项目中添加 4 个文件夹:

  1. Your Project\src\main\resources\

    \local > db.properties
    \integration > db.properties
    \deploy > db.properties
    \Default > db.properties
    
  2. 在pom.xml中添加:

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

     <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)
    

比使用配置文件更好的是在不接触 pom 的情况下更具可扩展性。

在你的情况下只是本地和远程:

    local/db.properties
            user=aaaa
            password=aaaa
            host=127.0.0.0

    remote/db.properties
            user=rrrrr
            password=rrrrr
            host=1.2.3.4