首页 > 解决方案 > 强制 @Autowired 弹簧靴和 webFlux

问题描述

我的应用程序使用并spring boot嵌入。webfluxtomcat

我使用包含一些 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>

注意:应用程序的打包是一场战争。

该组件缺少初始化导致 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]

标签: javaspring-boottomcatautowiredservletcontextlistener

解决方案


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

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

像这样:

@ServletComponentScan
@SpringBootApplication
public class SpringBootApp {

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

}

推荐阅读