2013-10-22 35 views
0

的情況下我有這個類:例外發送上下文初始化事件監聽器

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 

這個問題的原因是什麼?

如何解決?

UPDATE

<?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" /> 

是如此。

UPDATE

@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開始

消息

UtilService位置: enter image description here

從配置字符串:

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

一將此代碼添加到@Configuration類中

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

我看到舊錯誤。

更新2

我修改我的代碼,你的建議。我很困惑:

VARIANT1:

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(); 

      } 
} 

我看到老堆棧跟蹤。

爲什麼?

+0

張貼您的春天配置n文件 –

回答

0

確保您在Spring配置文件中啓用了組件掃描。強制掃描標籤應該指向包含UtilService的包。我想知道UtilService目前還沒有初始化爲Spring bean,因此它不適合自動裝配。

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

嘗試註冊ApplicationWebListener在你的Spring配置的bean,我不知道這是否會工作,但爲了在一個類自動裝配一個字段,這個類必須是一個bean。 Spring不能將bean自動裝入類未作爲IOC容器的一部分實例化的類中。

還有另一種方法。 Spring提供了一個ApplicationListener接口,它可以由類實現,然後註冊爲bean。 ApplicationListener將在應用程序生命週期的各個階段被調用,例如啓動,重新啓動和關閉。

這裏是ApplicationListener的例子:

Listener Example

而且在配置文件中註冊該偵聽器的一個例子,它必須是調度員的配置文件:

Configuration

documentation

+0

我有 – gstackoverflow

+0

** Kevin Bowersox **,請閱讀我的更新 – gstackoverflow

+0

@gstackoverflow DatabaseHelper需要是一個自動裝入的bean applicationlistener –

相關問題