我有一个球衣 2 项目,其中 Guice 用于 DI(通过 hk2 桥)。Spring JDBC 用于 DB 调用,并通过 Guice 进行配置。我正在使用嵌入式 tomcat 在本地运行它。此设置适用于应用程序,即我能够访问我的球衣资源中的数据库
现在我想为需要数据库访问以进行初始设置的应用程序编写测试用例,但我在注入的对象上得到了NullPointerException 。
主文件(这里注入给出空值)
public class StartApp {
@Inject
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) throws Exception {
startTomcat();
}
private static void startTomcat() throws Exception {
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
String webPort = System.getProperty("app.port", "8080");
tomcat.setPort(Integer.valueOf(webPort));
tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
tomcat.start();
new StartApp().initDatabase();
tomcat.getServer().await();
}
public void initDatabase() throws Exception {
String sql = new String(Files.readAllBytes(Paths.get(StartApp.class.getClassLoader().getResource("db_base.sql").toURI())), "UTF-8");
jdbcTemplate.execute(sql);
}
}
JdbcTemplate 注入仅在此处失败。在实际的球衣资源中,它工作正常。
web.xml(仅显示 guice 部分)
<filter>
<filter-name>Guice Filter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Guice Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>MyGuiceServletContextListener</listener-class>
</listener>
MyGuiceServletContextListener
public class MyGuiceServletContextListener extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(JdbcTemplate.class).toProvider(JdbcTemplateProvider.class).in(Scopes.SINGLETON);
}
});
}
}
JerseyConfig
public class JerseyConfig extends ResourceConfig {
@Inject
public JerseyConfig(ServiceLocator serviceLocator, ServletContext servletContext) {
packages("resources");
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector((Injector) servletContext.getAttribute(Injector.class.getName()));
}
}