如何使用maven为不同的配置文件执行任务

时间:2016-04-13 13:06:41

标签: java maven-2

我是Maven的新手。

我想为不同的用户执行数据库连接,所以我的问题是我应该在哪里提供这个JDBC连接以及如何为不同的用户提供这种连接?

我知道如何为不同的用户提供配置文件,但我应该在哪里执行数据库连接以及如何调用它?

1 个答案:

答案 0 :(得分:0)

最佳方法会使您的数据库连接属性(如用户名/密码,网址等)在外部。在配置文件中,您可以为每个用户定义属性的值,并使用maven资源过滤来设置它们。

在您的maven项目中,您将拥有一个配置目录(在src/config/settings.prp中),例如包含以下条目:

userName = ${userName}
password = ${password}
db-driver = ${dbDriver}
db-url = ${dbUrl}

在pom中你会有

<project ...>
    <build>
        <plugins>
           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-resources-plugin</artifactId>
               <version>2.7</version>
               <executions>
                   <execution>
                       <id>filter-db-settings</id>
                       <goals>
                           <goal>copy-resources</goal>
                       </goals>
                       <configuration>
                           <outputDirectory>${project.build.directory}/config</outputDirectory>
                           <resources>
                               <resource>
                                   <directory>${project.basedir}/src/config</directory>
                               </resource>
                               <filtering>true</filtering>
                           </resources>
                       </configuration> 
                   </execution>
               </executions>
           </plugin>
        <plugins>
    </build>

    <profiles>
        <profile>
            <id>user-A</id>
            <properties>
                <userName>userA</userName>
                <password>secret</password>
                <dbDriver>com.driver.db</dbDriver>
                <dbUrl>jdbc://db-url</dbUrl>
            </properties>
        </profile>
    <profiles>
</project>

该插件将过滤src/config中的文件,并使用您的个人资料中指定的值替换maven占位符。由于配置文件包含密码,您可以将其移至settings.xml,以便不会将项目本身检入,也可能会将密码泄露给不受欢迎的各方。

警告: Haven未验证上面的插件,因此可能包含小错误。

最好将属性文件 NOT 放在生成的工件中。通过这样做,您可以自由地为不同的用户使用相同的工件,并且您需要更改的唯一内容是外部属性文件中的属性(将在工件旁边提供给用户)。

以下文章介绍了如何使用spring Externalized Configuration外部化属性。