【发布时间】:2016-10-10 18:23:35
【问题描述】:
我正在开发基于 spring 和 servlet 的应用程序。 我的要求是从数据库加载数据并存储在ehcache中。我编写了一个监听器,一旦jboss服务器启动就会调用它。但问题是在我的应用程序中,我们使用 spring hibernate 类连接到数据库并从数据库加载数据。 根据要求,必须从数据库中检索数据并存储在缓存对象(ehcache)中。但是当加载侦听器类时,尚未加载其他 xml 配置文件(applicationContext.xml..),我们配置数据源详细信息以连接到数据库。以下是我的代码:
监听类。
import net.sf.ehcache.*;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/imports
public class MyInitializationListener extends HibernateDaoSupport implements ServletContextListener {
/** Singleton instance of CacheManager. */
private static CacheManager singletonManager = null;
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("--ServletContextListener destroyed*--");
}
private static CacheManager getInstance() {
if (singletonManager == null) {
singletonManager = CacheManager.create();
}
return singletonManager;
}
private Cache getCache() {
Cache cache = null;
cache = MyInitializationListener.getInstance().getCache("myCache");
return cache;
}
// Run this before web application is started
public void contextInitialized(ServletContextEvent arg0) {
final Cache cache = getCache();
final String dbValue = getDBValue();
//logic here
}
public String getDBValue() throws DataLayerException{
//logic to get the value from database
}
以下是例外:
ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/eas-webservice/ivr]] Exception sending context initialized event to listener instance of class com.data.listener.MyInitializationListener
java.lang.NullPointerException
以前有没有人遇到过这种情况。当服务器启动时,连接到数据库并从数据库中获取值并存储在缓存中的最佳方法是什么?建议会很有帮助。
--已编辑--
我在服务器启动时尝试使用@PostConstruct 来调用 loadData() 的方法。但是当我签入日志文件时,打印语句不存在,这表明在服务器启动时没有调用该方法开始了。
@Component
public class MyDataStore {
@PostConstruct
public void loadData()
{
System.out.println("--In @postconstruct, loadData-");
}
}
【问题讨论】:
标签: java spring servlets jboss ehcache