我如何 运行 来自不同模块的 spring-boot-rest 应用程序,例如:在 CI 中通过 Maven 构建?

How do I run a spring-boot-rest application from a different module eg: in CI build via Maven?

   |--Integration tests 
   |--Spring boot rest application

我有两个模块, Spring 启动应用程序是我的终点, 它 运行 在它自己的嵌入式 tomcat 上,我希望能够 运行 它作为集成测试的 Maven 构建的一部分,并在其上进行 运行 集成测试。

我的问题是,有没有办法 运行 spring 通过 maven 从不同的模块启动应用程序?

在 Spring boot 的网站上,我只能看到 运行 使用 spring-boot-maven 通过其自己的 pom 启动 spring-boot 应用程序的示例-plugin,但不是通过 运行 通过在执行中指定 jar 文件将应用程序作为不同模块的一部分。

是的,有几种方法可以完成您的要求,例如:

  1. 在测试中使用 @SpringBootTest 注释 classes(自 Spring Boot 1.4);
  2. 从您的测试中以编程方式启动 Spring 引导应用程序。

第一个是我最喜欢的,也是最简单的一个,但它当然只适用于单元测试的上下文。这是一个例子。

假设您的 REST 模块中有一个名为 Application 的 class,并用 @SpringBootApplication 注释。您可以通过在集成测试模块中定义这样的测试来测试端点:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, properties = {"my.overriden.property=true"} )
public class RestEndpointTest
{
    // ...
}

通过这样做,应用程序的整个上下文将启动。然后,您可以根据需要进一步配置测试,同时覆盖一些属性(请参阅 my.overridden.property)。

或者,您可以在测试模块中定义自己的配置,从其他模块引用任何必需的 class,例如:

@Configuration
@ComponentScan(basePackageClasses = {BaseClass.class})
@EnableJpaRepositories
@EntityScan
@EnableAutoConfiguration
public class SupportConfiguration
{
    @Bean
    public ARequiredBean bean()
    {
        return new ARequiredBean();
    }

    // etc...
}

并像处理任何其他上下文一样使用它:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SupportConfiguration.class)
public class CustomTest
{
    // ...
}

另一种方法是以编程方式启动 REST 应用程序的一个实例,如下所示:

public static void main(String[] args) throws IOException
    {
        try (ConfigurableApplicationContext context = SpringApplication.run(Application.class, args))
        {
            log.info("Server Started. Press <Enter> to shutdown...");
            context.registerShutdownHook();
            BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
            inReader.readLine();
            log.info("Closing application context...");
            context.stop();
        }
        log.info("Context closed, shutting down. Bye.");
        System.exit(0);
    }