gpt4 book ai didi

spring-boot - 关于spring boot如何正确禁用web环境

转载 作者:行者123 更新时间:2023-12-03 14:40:25 25 4
gpt4 key购买 nike

Spring启动非Web应用程序,启动时出现以下错误

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:185) ~[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]

然后我尝试了以下方式
new SpringApplication().setWebEnvironment(false);

然后启动它仍然有上述错误。

然后试过
@SpringBootApplication(exclude={SpringDataWebAutoConfiguration.class})

但仍然有同样的错误。

最后我尝试在 application.properties 中添加以下配置
spring.main.web-environment=false

这次它起作用了。

为什么前两种方式不起作用?

最佳答案

这个答案已经过时了。请注意 Spring Boot 2.0 的其他答案

Spring Boot 1.x 的原始答案:

此配置不起作用的原因是因为这是两个不同的实例:

new SpringApplication().setWebEnvironment(false); 
SpringApplication.run(SpringBootDisableWebEnvironmentApplication.class, args);

您正在禁用 setWebEnvironment(false)new SpringApplication()对象并调用静态方法 run()SpringApplication.run(...)这是不同的。

我想出了 3 种方法来做到这一点:
@SpringBootApplication
public class SpringBootDisableWebEnvironmentApplication implements CommandLineRunner{


public static void main(String[] args) throws Exception {

// Method#1: Using SpringApplicationBuilder.

SpringApplication springApplication =
new SpringApplicationBuilder()
.sources(SpringBootDisableWebEnvironmentApplication.class)
.web(false)
.build();

springApplication.run(args);

//--------------------------------------------------------

// Method#2: Using SpringBootDisableWebEnvironmentApplication.

// SpringBootDisableWebEnvironmentApplication springBootDisableWebEnvironmentApplication =
// new SpringBootDisableWebEnvironmentApplication();
// springBootDisableWebEnvironmentApplication.run(args);

//--------------------------------------------------------

// Method#3: Using SpringApplication().

// SpringApplication springApplication = new SpringApplication();
// springApplication.setWebEnvironment(false);
//
// Set<Object> sources = new HashSet<>();
// sources.add(SpringBootDisableWebEnvironmentApplication.class);
// springApplication.setSources(sources);
// springApplication.run(args);

//--------------------------------------------------------

}

@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello, Spring Boot gives many options ;)");
}
}

这是完整的工作 Project .

而且您不需要排除以下配置:
@SpringBootApplication(exclude = {EmbeddedServletContainerAutoConfiguration.class, 
WebMvcAutoConfiguration.class})

因为你没有 spring-boot-starter-web您的 pom.xml 中的依赖性
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

关于spring-boot - 关于spring boot如何正确禁用web环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37187519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com