Dropwizard 1.2升级至2.0.x版本DI依赖注入失效问题咨询
Dropwizard 1.x升级2.0.x后DI字段注入失效解决方案
问题根因
Dropwizard 2.0版本升级了依赖的Jersey版本,新版Jersey默认不再对用户手动实例化后注册的资源对象做字段注入处理。你当前的代码是自行创建SessionResource实例后再注册到Jersey,因此@Inject标注的responder字段不会被自动赋值,1.x版本的低版本Jersey默认支持该场景的注入,所以升级后出现null的问题。
可行解决方案
方案1(推荐):将资源完全交給DI容器管理
将所有依赖都绑定到DI容器,直接注册资源类而非手动实例化,同时改为更规范的构造器注入避免字段注入的潜在问题:
- 在自定义
AbstractBinder中补充AuthenticationService的绑定逻辑:
environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(configuration.getResponder()).to(Responder.class); // 新增AuthenticationService绑定 bind(authenticationService).to(AuthenticationService.class); } });
- 修改
SessionResource为构造器注入:
@Path("/sessions") @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON, "application/v1+json"}) @Timed public class SessionResource { private final Responder responder; private final AuthenticationService authenticationService; @Inject public SessionResource(Responder responder, AuthenticationService authenticationService) { this.responder = responder; this.authenticationService = authenticationService; } // 接口方法定义 }
- 资源注册改为类注册:
environment.jersey().register(SessionResource.class);
方案2:手动触发已有实例的注入
如果你有特殊逻辑必须自行实例化SessionResource,可以调用Jersey提供的注入方法主动填充@Inject字段:
SessionResource sessionResource = new SessionResource(authenticationService); // 主动触发注入逻辑填充标注了@Inject的字段 environment.jersey().inject(sessionResource); environment.jersey().register(sessionResource);
内容的提问来源于stack exchange,提问作者Panos Karampis
相关产品推荐
相关产品推荐

