exception de l'envoi de contexte initialisé événement à l'auditeur instance de la classe
J'ai cette classe:
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;
}
}
et ce 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();
}
}
Quand je lance mon application, je vois suivantes:
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
Ce que la cause de ce problème?
Comment résoudre ce problème?
Mise à JOUR
<?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>
et ce:
<import resource="classpath:spring/BeanConfig.xml" />
<!-- Файл с настройками Security -->
<import resource="security_config.xml" />
et ce:
<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" />
que donc.
Mise à JOUR
@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");
}
}
ce code fonctionne bien. Quand je lance mon application, je vois
servletContextListener commencé
message
UtilService emplacement:
chaîne de configuration:
<context:component-scan base-package="com.epam.hhsystem.services" />
après l'ajout de ce code @classe de Configuration
@Bean
ApplicationWebListener getApplicationWebListener(){
return new ApplicationWebListener();
}
Je vois la vieille erreur.
Mise à JOUR 2
Je refactoriser mon code pour vos conseils. Je suis confus:
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();
}
}
Cette variante fonctionne bien, mais c'est l'architecture d'horreur
variante 2:
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
DatabaseHelper.fillEmptyTables();
}
}
Je vois des vieux stacktrace.
pourquoi?
- Postez votre fichier de configuration spring
Vous devez vous connecter pour publier un commentaire.
Assurez-vous que vous avez la composante à balayage activé dans le fichier de configuration Spring. La partie d'analyse de la balise doit pointer vers le paquet contenant
UtilService
. J'aimerais comprendre queUtilService
est actuellement pas initialisé, comme un Ressort de haricot, il n'est pas un candidat pour permettra à l'autowiring.Essayez d'inscrire le
ApplicationWebListener
comme un haricot dans votre Configuration Spring, je ne suis pas sûr si cela va fonctionner, mais pour autowire un champ dans une classe, cette classe doit être un haricot. Le printemps ne peut pas autowire les haricots dans des classes qui n'ont pas été instancié dans le cadre du conteneur IOC.Il y a une autre approche. Spring fournit un
ApplicationListener
interface peut être implémentée par une classe et est enregistré comme un haricot. LeApplicationListener
seront appelés à différents moments au cours du cycle de vie des applications comme le démarrage, redémarrage et arrêt.Voici un exemple de la
ApplicationListener
:Exemple D'Écouteur
Et un exemple de l'enregistrement d'auditeur dans votre fichier de configuration, qui doit être le répartiteur du fichier de configuration:
Configuration
Et la la documentation
ServletContextListener.contextInitialized()
appelle tous les haricots ne sont pas autocâblés