我正在尝试在下拉向导应用程序中使用Weld-SE进行依赖项注入。我可以引导Weld并在Application类中注入,如下所示:
public class App extends Application<AppConfig> {
@Inject NameService service;
@Inject RestResource resource;
public static void main(String[] args) throws Exception {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
App app = container.instance().select(App.class).get();
app.run(args);
weld.shutdown();
}
}我在一个单独的类中为RestResource编写了一个生成器方法,这也被注入了罚款。但是,在资源类中,没有注入服务:
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public class RestResource {
@Inject NameService service;
@GET
public String test() {
return service.getName();
}
}这里的服务总是空的。有人知道怎么做吗?
发布于 2014-11-05 12:04:21
Dropwizard正在使用泽西,其依赖注入是基于HK2而不是CDI的。因此,你需要在两者之间架起一座桥梁。这就是jersey-gf-cdi的作用所在:
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
</dependency>你只需要把那个罐子放在类路径里就行了。您可以在这里看到Jetty的配置:https://github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/pom.xml
下面是JAX-RS资源中的CDI bean注入示例:https://github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/src/main/java/io/astefanutti/cdeye/web/BeansResource.java。
发布于 2015-05-04 13:36:07
对于DropWizard 0.8.1和Weld 2.2,程序如下:
1)向pom.xml添加依赖关系:
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-core</artifactId>
<version>2.2.11.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-cdi1x</artifactId>
<version>2.17</version>
</dependency>
<!-- the following additional dependencies are needed by weld -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>2)将beans.xml文件添加到src/main/resources/main中,并为应用程序包添加一个包含过滤器。这是特别需要时,使用阴影罐-没有过滤器焊接将扫描在阴影罐中的每一个类。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:weld="http://jboss.org/schema/weld/beans">
<weld:scan>
<weld:include name="com.example.**" />
</weld:scan>
</beans>3)在应用程序类中注册Weld的侦听器
@Override
public void run(Configuration conf, Environment env) throws Exception {
env.servlets().addServletListeners(new org.jboss.weld.environment.servlet.Listener());
}https://stackoverflow.com/questions/26747033
复制相似问题