spring-boot - 如何禁用 TomcatServletWebServerFactory 的 SpringBoot 自动配置以便自定义 spring-starter 提供它?

标签 spring-boot tomcat embedded-tomcat-8 spring-boot-configuration spring-starter

所以我正在编写自己的 SpringBootStarter,它应该在 SpringBoot 应用程序的嵌入式 tomcat 中启用 JNDI 查找。

我的示例 SpringBoot 应用程序依赖于我的自定义 SpringBootStarter,而后者又依赖于 spring-boot-starter-web。如果我在示例 SpringBoot 应用程序中创建如下所示的配置类,一切都会完美运行:

@Configuration
public class SampleSpringBootAppConfig {


@Bean
public TomcatServletWebServerFactory tomcatFactory() {
    return new TomcatServletWebServerFactory() {
        @Override
        protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
            System.out.println("CONFIGURING CUSTOM TOMCAT WEB SERVER FACTORY ");
            tomcat.enableNaming();
            return super.getTomcatWebServer(tomcat);
        }

        @Override
        protected void postProcessContext(Context context) {



            ContextResource resource = new ContextResource();
            resource.setName("myDataSource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "org.postgresql.Driver");

            resource.setProperty("url", "jdbc:postgresql://localhost:5432/postgres");
            resource.setProperty("username", "postgres");
            resource.setProperty("password", "postgres");

            context.getNamingResources()
                    .addResource(resource);

        }
    };
}

因为 SpringBoot 找到一个自定义 Bean,所以不会有一个自动配置的默认 Bean/它被覆盖并且成功启用了 JNDI。

但是,一旦我将此 Bean 配置提取到我的自定义 SpringBoot Starter 的自动配置模块中,就会在尝试启动示例 SpringBoot 应用程序时抛出以下异常:

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans : tomcatServletWebServerFactory,tomcatFactory

我认为这是由于 SpringBoot 没有找到自定义的 Bean,因此创建了一个自动配置的默认 Bean,它也不会被覆盖。所以现在将有两个 ServletWebServerFactory beans,默认的一个和我的自动配置模块中的一个。

到目前为止我尝试了什么(无济于事):

  • 用@Primary 注释我的自定义 Bean
  • 将 spring.main.allow-bean-definition-overriding 设置为 true

有什么方法可以让 SpringBoot 不初始化自动配置的默认 bean,或者任何其他可能的解决方案吗?

最佳答案

试试这个 @AutoConfigureBefore(ServletWebServerFactoryAutoConfiguration.class)

关于spring-boot - 如何禁用 TomcatServletWebServerFactory 的 SpringBoot 自动配置以便自定义 spring-starter 提供它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58821412/

相关文章:

java - Spring Boot 社交媒体 - facebook 登录

java - Spring Boot 嵌入式 Tomcat 'allowLinking' 属性

spring - java.io.IOException : Broken pipe bringing down the embedded tomcat 8 app

spring - Ignite 和 Spring Boot

java - 如何使用Spring Boot引发自定义异常而不是500

java - 线程“kafka-生产者-网络-线程”中未捕获的异常 |生产者1

apache - catalina.sh jdpa start 不启动服务器

java - 使用健康检查或 ping 来提高 rest api 性能

java - 如何在没有任何请求、 session 等的情况下获取上下文?

java - 为什么 Spring-Boot 应用程序在创建 CXF SOAP 服务步骤时卡住?