如何防止spring-web的弹簧自动配置?

我正在使用spring-boot并在maven pom中添加spring-web依赖,以使用RestTemplate

现在spring尝试初始化EmbeddedServletContext 。 我该怎样预防呢?

 Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean. at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) at org.springframework.boot.SpringApplication.run(SpringApplication.java:957) at org.springframework.boot.SpringApplication.run(SpringApplication.java:946) Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean. at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:183) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:156) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) ... 8 more 

供参考: Spring Boot Reference Guide中记录了此用例:

并非所有Spring应用程序都必须是Web应用程序(或Web服务)。 如果要在main方法中执行某些代码,还要引导Spring应用程序来设置要使用的基础结构,那么使用Spring Boot的SpringApplicationfunction很容易。 SpringApplication根据它是否认为需要Web应用程序SpringApplication更改其ApplicationContext类。 您可以做的第一件事就是将servlet API依赖项留在类路径中。 如果您不能这样做(例如,您正在运行来自相同代码库的2个应用程序),那么您可以显式调用SpringApplication.setWebEnvironment(false) ,或者设置applicationContextClass属性(通过Java API或使用外部属性)。 您希望作为业务逻辑运行的应用程序代码可以作为CommandLineRunner实现,并作为@Bean定义放入上下文中。

application.properties:

 spring.main.web-environment=false #webEnvironment property 

第一招:

 public static void main(String[] args) throws Exception { ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class) .web(false) .run(args); } 

第二:

 @Configuration @EnableAutoConfiguration(exclude = WebMvcAutoConfiguration.class) public class Application { 

这适用于Spring Boot 2.x.

 public static void main(String[] args) { new SpringApplicationBuilder(MyApplication.class) .web(WebApplicationType.NONE) .build() .run(args); } 

虽然禁用Web环境的传统方法(如@Tim的回答中提到的)仍然适用于Spring Boot 2.x,但是新的首选方法是设置以下属性

spring.main.web-application-type=none

以下是定义允许值的枚举