'exception sending context initialized event to listener instance of class

I have this class:

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; 
    }
}

and this listener:

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

When I run my application I see following:

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

What the cause of this problem?

How to fix it?

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>

and this:

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

and this:

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

that so.

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");
    }
}

this code works good. When I run my application I see

servletContextListener started

message

UtilService location: enter image description here

string from configuration:

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

after adding this code to @Configuration class

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

I see old error.

UPDATE 2

I refactor my code for your advice. I am confused:

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


    }

This variant works good but it is architecture horror

variant 2:

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

            }
}

I see old stacktrace.

why?



Solution 1:[1]

Make sure you have component scanning enabled in the Spring configuration file. The compenent scan tag should point to the package containing UtilService. I would fathom that UtilService is currently not initialized as a Spring bean making it not a candidate for autowiring.

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

Try registering the ApplicationWebListener as a bean in your Spring Configuration, I'm not sure if this will work, but in order to autowire a field in a class, that class must be a bean. Spring cannot autowire beans into classes that were not instantiated as part of the IOC container.

There is another approach. Spring provides an ApplicationListener interface which can be implemented by a class and then registered as a bean. The ApplicationListener will be called at various points during the applications lifecycle such as startup, restart and shutdown.

Here is an example of the ApplicationListener:

Listener Example

And an example of registering that listener in your configuration file, which must be the dispatcher's configuration file:

Configuration

And the documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1