【发布时间】:2011-12-21 02:08:22
【问题描述】:
我正在尝试使用 Jersey、Rest、Tomcat、c3p0 等构建应用程序。
我有一个 ConfigurationManager 类,我想成为一个热切的单例,而连接池类我也想成为一个热切的单例。连接池正在使用带有注入注释的配置管理器,但连接池中的配置管理器为空,由于某种原因它没有注入。它是由 guice 实例化的,我可以从日志中看到这一点。
当我将它注入 Rest 资源类时,它按预期工作。
当我将它注入 StartupServlet 时,它也是空的。
如果有人能对此有所了解,我将不胜感激。您可以在下面找到 web.xml 和类。
web.xml
<servlet>
<servlet-name>StartupServlet</servlet-name>
<servlet-class>net.nemanjakovacevic.ft1p.configuration.StartupServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- set up Google Guice Servlet integration -->
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>net.nemanjakovacevic.ft1p.configuration.GuiceServletConfiguration</listener-class>
</listener>
GuiceServletConfiguration.java
public class GuiceServletConfiguration extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new GuiceConfigurationModule(), new JerseyServletModule() {
@Override
protected void configureServlets() {
/* bind the REST resources */
bind(Test.class);
serve("/*").with(GuiceContainer.class);
}
});
}
}
GuiceConfigurationModule.java
public class GuiceConfigurationModule extends AbstractModule {
@Override
protected void configure() {
bind(ConfigurationManager.class).asEagerSingleton();
bind(ConnectionPool.class).asEagerSingleton();
}
}
配置管理器
public class ConfigurationManager {
// Nothing important here, loading from config file
}
ConnectionPool(这里不工作)
public class ConnectionPool {
private static final Logger log = LoggerFactory.getLogger(ConnectionPool.class);
private ComboPooledDataSource pooledDataSource;
@Inject
private ConfigurationManager cManager;
public ConnectionPool() {
log.info("Initializing c3p0 coonection pool");
pooledDataSource = new ComboPooledDataSource();
try {
//Null pointer exception here, cManager is null
pooledDataSource.setDriverClass(cManager.getJdbcDriverClassName());
pooledDataSource.setJdbcUrl(cManager.getJdbcUrl());
pooledDataSource.setUser(cManager.getDatabaseUsername());
pooledDataSource.setPassword(cManager.getDatabasePassword());
} catch (PropertyVetoException e) {
log.error("Exception during c3p0 initalisation.", e);
//TODO obrada izuzetaka
}
}
}
Test.java(在这里工作)
@Path("/test")
public class Test {
@Inject
ConfigurationManager cManager;
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg){
// cManager is not null, it's injected as it should be
String output = cManager.getDatabaseHostName();
return Response.status(200).entity(output).build();
}
}
【问题讨论】: