如何使用 Tomcat 作为具有 Maven 测试范围的 Eclipse 服务器

how to use Tomcat as Eclipse Server with Maven test scope

在使用 Eclipse 4.4.1 的 J2EE 项目中,我们使用本地 Tomcat 来测试我们的应用程序。
它在 Eclipse Servers 视图中配置。
生产平台已经集成了一个数据库驱动程序。本地测试环境我们用这个。

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.3-1102-jdbc41</version>
    <scope>test</scope>
</dependency>

但只有更改范围才能编译,否则它不会起作用。使用编译范围,在 Eclipse 中配置的本地 Tomcat 可以正确启动,而不会抱怨缺少 jdbc 驱动程序。
是否可以在测试范围内将 Tomcat 服务器配置为 运行?以调试模式启动并不能解决这个问题。

您将 Maven 依赖范围用于错误目的。来自 Maven POM reference:

test - this scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

您需要的是个人资料。来自 Maven POM reference:

A new feature of the POM 4.0 is the ability of a project to change settings depending on the environment where it is being built. A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment. Or dependencies may be pulled from different repositories based upon the JDK version used.

因此,尝试向您的测试环境添加一个配置文件,如下所示:

<profiles>
    <profile>
        <id>test</id>
        <dependencies>
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>9.3-1102-jdbc41</version>
            </dependency>
        </dependencies>
    </profile>
</profiles>

要在 eclipse 上激活此配置文件,请执行以下操作:右键单击您的项目 --> Maven --> Select Maven 配置文件...(在 windows 上,只需 CTRL + ALT + )。然后,select个人资料:

在命令行中,您可以执行类似这样的操作来激活 test 配置文件:

mvn <lifecycles> -Ptest