强制@Autowired spring boot 和 webFlux

问题描述

我的应用程序使用嵌入了 spring bootwebfluxtomcat

我使用包含一些 servlet 侦听器的第三个库。

应用程序启动时,injector 的侦听器属性 Bagservletcontextlistener 返回 null。

@WebListener
public class Bagservletcontextlistener implements servletcontextlistener {
    @Autowired
    private BagInjector injector;

    @Override
    public void contextinitialized(ServletContextEvent event) {
        this.injector.inject();

    }
}

如何通过 @bean 或其他方式强制初始化此组件?

我的一块pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

注意:app的打包是一场战争。

该组件未初始化导致contextinitialized方法中出现空指针异常。

[ERROR ] SRVE0283E: Exception caught while initializing context: java.lang.NullPointerException at com.devIo.ee.Bagservletcontextlistener.contextinitialized(Bagservletcontextlistener.java:33) at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:2391) at [internal classes]

解决方法

您没有告诉 Spring Boot 扫描您的 BagServletContextListener 类。 @WebListener 没有做到这一点。

@ServletComponentScan 添加到您的 SpringBootApplication 类以确保扫描 BagInjector - Spring 知道如何为您自动装配它。

像这样:

@ServletComponentScan
@SpringBootApplication
public class SpringBootApp {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class,args);
    }

}