有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

向类的侦听器实例发送上下文初始化事件时发生java异常

我有这门课:

public class DatabaseHelper {
    @Autowired
    static UtilService utilService;

    public static void fillEmptyTables(){
        if(!isSkillsInDatabase()){
            utilService.addGeneratedSkill();
        }
        if(!isEventTypesInDatabase()){
            utilService.addGeneratedEventType();
        }
        if(!isEventStatusesInDatabase()){
            utilService.addGeneratedEventStatus();
        }

    }
    public static boolean isSkillsInDatabase(){
        return utilService.getAllSkills().size() != 0; 
    }
    public static boolean isEventStatusesInDatabase(){
        return utilService.getAllEventStatuses().size() != 0; 
    }
    public static boolean isEventTypesInDatabase(){
        return utilService.getAllEventTypes().size() != 0; 
    }
}

这位听众:

@WebListener
public class ApplicationWebListener implements ServletContextListener {
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("ServletContextListener destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("ServletContextListener started");
        DatabaseHelper.fillEmptyTables();
    }
}

当我运行应用程序时,我看到以下内容:

INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 10029 ms
ServletContextListener started
22.10.2013 13:21:16 org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class com.epam.hhsystem.web.controllers.ApplicationWebListener
java.lang.NullPointerException
    at com.epam.hhsystem.util.DatabaseHelper.isSkillsInDatabase(DatabaseHelper.java:25)
    at com.epam.hhsystem.util.DatabaseHelper.fillEmptyTables(DatabaseHelper.java:13)
    at com.epam.hhsystem.web.controllers.ApplicationWebListener.contextInitialized(ApplicationWebListener.java:19)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
22.10.2013 13:21:16 org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart

这个问题的原因是什么

如何修复它

更新

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.epam.hhsystem.web.controllers"/>


</beans:beans>

这是:

<import resource="classpath:spring/BeanConfig.xml" />
    <!-- Файл с настройками Security -->
    <import resource="security_config.xml" />

这是:

<context:annotation-config />

    <!--ищем тут разные аннотации (например @service)  -->
    <context:component-scan base-package="com.epam.hhsystem.jpa" />
    <context:component-scan base-package="com.epam.hhsystem.util" />
    <context:component-scan base-package="com.epam.hhsystem.services" />

    <context:component-scan base-package="com.epam.hhsystem.web.controllers" />



    <!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) -->
    <import resource="data.xml" />

的确如此

更新

@WebListener
public class ApplicationWebListener implements ServletContextListener {
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("ServletContextListener destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("ServletContextListener started");
    }
}

这段代码运行良好。当我运行应用程序时,我看到

servletContextListener started

信息

UtilService位置: enter image description here

配置中的字符串:

<context:component-scan base-package="com.epam.hhsystem.services" />

将此代码添加到@Configuration class之后

    @Bean
    ApplicationWebListener getApplicationWebListener(){
        return new ApplicationWebListener();
    }

我看到了老错误

更新2

为了你的建议,我重构了我的代码。我很困惑:

变量1:

   public class MyApplicationListener  implements ApplicationListener<ContextRefreshedEvent> {
            @Autowired
            UtilService utilService;

            public  void fillEmptyTables(){
                if(!isSkillsInDatabase()){
                    utilService.addGeneratedSkill();
                }
                if(!isEventTypesInDatabase()){
                    utilService.addGeneratedEventType();
                }
                if(!isEventStatusesInDatabase()){
                    utilService.addGeneratedEventStatus();
                }

            }
            public  boolean isSkillsInDatabase(){
                return utilService.getAllSkills().size() != 0; 
            }
            public  boolean isEventStatusesInDatabase(){
                return utilService.getAllEventStatuses().size() != 0; 
            }
            public  boolean isEventTypesInDatabase(){
                return utilService.getAllEventTypes().size() != 0; 
            }    

            @Override
            public void onApplicationEvent(ContextRefreshedEvent event) {
                fillEmptyTables();
        }


    }

这种变体工作得很好,但却令人恐惧

备选案文2:

public class MyApplicationListener  implements ApplicationListener<ContextRefreshedEvent> {
                @Override
                public void onApplicationEvent(ContextRefreshedEvent event) {
                           DatabaseHelper.fillEmptyTables();

            }
}

我看到了老斯塔克崔斯

为什么


共 (1) 个答案

  1. # 1 楼答案

    确保在Spring配置文件中启用了组件扫描。compent扫描标签应该指向包含UtilService的包。我想知道UtilService目前还没有初始化为Springbean,因此它不是自动连线的候选对象

    <context:component-scan base-package="package.containing.UtilService" />
    

    尝试在Spring配置中将ApplicationWebListener注册为bean,我不确定这是否有效,但为了自动连接类中的字段,该类必须是bean。Spring无法将bean自动连接到未作为IOC容器的一部分实例化的类中

    还有另一种方法。Spring提供了一个ApplicationListener接口,可以由类实现,然后注册为bean。在应用程序生命周期的不同阶段,例如启动、重新启动和关闭,将调用ApplicationListener

    下面是ApplicationListener的一个例子:

    Listener Example

    以及在配置文件(必须是dispatcher的配置文件)中注册该侦听器的示例:

    Configuration

    documentation