我有一个运行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启动应用程序的任何测试,那么您的测试(以及您的构建版本)也将被阻止。
即使您可以将-Dmaven.test.skip=true
参数传递给跳过测试(如this answer中所述),但仍然意味着该特定测试已被破坏。如果您不需要它,请删除它,或者通过执行以下操作确保在测试期间不调用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。
我通过在生成JAR时跳过测试来解决它:
mvn package -Dmaven.test.skip=true
mvn package
正在调用我的测试,它在内部初始化了所有bean,并且作为初始化的一部分,Spring调用@PostConstruct
方法。
首先,您需要在pom文件中更新。
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.eg</groupId>
<artifactId>eg</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
然后运行此命令(mvn package -Dmaven.test.skip = true)