我有一个 spring-boot 应用程序需要:
- 可部署为 servlet 容器中的 war
- 可以通过 `mvn spring-boot:run`` 运行
我还希望能够通过右键单击 main
并运行它来在我的 IDE(Eclipse 或 IntelliJ IDEA 社区)中运行该应用程序。
这是我的 pom.xml 中有趣的部分(请注意,我没有继承自 spring-boot-starter-parent pom):
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
...
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
这是我的 SpringBootServletInitializer
:
@Configuration
@EnableAutoConfiguration
@ComponentScan("com.company.theproject")
public class Application extends SpringBootServletInitializer
{
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
{
return application.sources(Application.class);
}
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
在 IDE 中运行 main 时出现以下错误:
org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:183) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:156) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
... 12 common frames omitted
似乎 mvn spring-boot:run
做了一些直接运行 main
时不会发生的魔法。
从 spring-boot-starter-tomcat
依赖项中删除 provided
作用域修复了这个问题,但当 war 在 servlet 容器内运行时会导致麻烦。
目前我发现的唯一“修复”是在 IntelliJ IDEA 中运行 mvn spring-boot:run
而不是直接运行 main。虽然这是一个可以接受的解决方法,但我仍然想知道为什么它不起作用以及是否可以修复。
最佳答案
受 https://youtrack.jetbrains.com/issue/IDEA-140041 强烈启发的解决方法是用测试类路径(包括嵌入式 servlet。)启动您的主类。
步骤(IntelliJ 16):
-
Run
->Edit Configurations
->Add new configuration
-> 选择Application
类型。 - 设置
Main class
至<your.main.class>
- 设置
Use classpath of module
至<*>_test
(测试模块!) -
Ok
和Run
它!
关于java - 使用 IDE 运行 Spring-boot 的 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38391531/