第一个片段(不起作用)
配置:
@Configuration
public class UiConfig {
@Bean //if i doesn't write this bean result will not change
ApplicationWebListener getApplicationWebListener(){
return new ApplicationWebListener();
}
}
听众:
@WebListener
public class ApplicationWebListener implements ServletContextListener {
@Autowired
DatabaseHelper databaseHelper;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
databaseHelper.fillEmptyTables();
}
}
结果:
java.lang.NullPointerException
at com.epam.hhsystem.web.controllers.ApplicationWebListener.contextInitialized(ApplicationWebListener.java:24)
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)
第二个片段:
配置:
@Configuration
public class UiConfig {
@Bean//if I doesn't write this bean MyApplicationListener code doesn't execute
MyApplicationListener getMyApplicationListener(){
return new MyApplicationListener();
}
}
听众:
public class MyApplicationListener implements
ApplicationListener<ContextRefreshedEvent> {
@Autowired
DatabaseHelper databaseHelper;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
databaseHelper.fillEmptyTables();
}
}
结果 - 方法调用和良好的工作。
数据库助手:
@Component
public class DatabaseHelper {
@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;
}
}
你能解释一下这些情况吗?