我正在努力为我的小 Web 应用程序获得某种 (c)di 工作。我放弃了使用 Weld,现在我正在尝试 hk2(它已经被 jersey 2 使用)。这是我的服务,它试图注入一些东西:
@ManagedBean
@Path("excelExport")
public class ExcelExportService {
@Inject
ExcelReport excelReport;
/**
*
* @param idString
* crucial to fetch the report
* @return excel document (xlsx) to be downloaded
*/
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public final Response getExcel(@QueryParam("id") final String idString) {
Long id;
try {
id = Long.valueOf(idString);
} catch (NumberFormatException e) {
return Response.status(Status.BAD_REQUEST).build();
}
return Response.ok(excelReport.getCompleteExcel(id), MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; filename=\"" + "report-" + id + ".xlsx" + "\"")
.build();
}
}
我不确定是否@ManagedBean
有必要。问题是:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=ExcelReport,parent=ExcelExportService,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1464117566)
所以注入根本不起作用。我按照此处的描述设置了 DI (请参阅接受的答案)。在我的情况下,活页夹看起来像这样:
@Override
protected void configure() {
bind(ExcelReport.class).to(ExcelReport.class);
bind(Data.class).to(DataDbImpl.class).in(Singleton.class);
}
我想我不需要 ExcelReport 的绑定,因为它有一个注入数据的构造函数——对吗?但这两种方式都行不通。
我的“主要”是这个
public class WebApp extends ResourceConfig{
public WebApp(){
register(Binder.class);
packages("true", "com.prodyna.reportExport.service");
}
}
和 web.xml:
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>reportExport</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.prodyna.WebApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>reportExport</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
那么如何正确设置 DI(我的第三次尝试将是 Guice)。
更新 我也不确定所需的依赖项。目前我包括了这个(根据提示更新):
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>2.16</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
.....