我有一个运行CLI应用程序的Springboot应用程序。
这是我的主要课程:
@SpringBootApplication
public class MyApplication {
@Autowired
GameClient gameClient;
@PostConstruct
public void postConstruct(){
gameClient.runGame();
}
public static void main(String[] args) {
SpringApplication.run(GameApplication.class, args);
}
}
当我运行命令mvn package
生成JAR时,Spring将执行该postConstruct()
方法并启动CLI应用程序,而不是正确生成JAR。
当我删除postConstruct()
JAR时,它已成功生成,但是我需要此方法,因为它负责运行我的CLI应用程序。
我该如何解决?
问题是gameClient.runGame()
似乎通过无限运行或请求用户输入来阻止您的测试。如果您有任何运行Spring Boot应用程序的测试,那么您的测试(以及您的构建)也会阻塞。
即使您可以传递-Dmaven.test.skip=true
参数以跳过测试(如本答案中所述),它仍然意味着特定测试已损坏。如果不需要,则将其删除,或者gameClient.runGame()
通过执行以下操作来确保在测试期间未将其调用:
将逻辑移到实现CommandLineRunner
(或ApplicationRunner
)接口的单独的类中:
@Component
public class GameRunner implements CommandLineRunner {
@Autowired
GameClient gameClient;
@Override
public void run(String...args) throws Exception {
gameClient.runGame();
}
}
之后,用注释为组件添加@Profile
注释,例如:
@Component
@Profile("!test") // Add this
public class GameRunner implements CommandLineRunner {
@Autowired
GameClient gameClient;
@Override
public void run(String...args) throws Exception {
gameClient.runGame();
}
}
通过使用@Profile
注释,您可以告诉Spring仅在某些配置文件处于活动状态时才加载组件。通过使用感叹号!
,我们告诉Spring仅在测试配置文件处于未激活状态时才加载组件。
现在,在测试中,您可以添加@ActiveProfiles("test")
注释。这将在运行测试时启用测试概要文件,这意味着GameRunner
将不会创建Bean。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句