【问题标题】:Injecting objects created via hk2+jersey returns null注入通过 hk2+jersey 创建的对象返回 null
【发布时间】:2014-09-04 06:13:25
【问题描述】:

我有以下资源类

@Path("/helloworld")
public class HelloWorldResource {
@Inject
private UserAuthorizationRepository userRepository;

@GET
public Response sayHello(@Context UriInfo uriInfo) 

以下是我对 UserAuthorizationRepository 的实现

public class UserAuthorizationRepositoryImpl implements UserAuthorizationRepository { 
@Inject
private MyUserIdToUserNameTable userIdToUserNameTable;
public String getUserName(Long userId) {
    userNameToUserIdTable.getUserName(userId)
}

并且我已将以下活页夹注册到 ResourceConfig

public class RepositoryBinder extends AbstractBinder {
@Override
protected void configure() {
    bind(new UserAuthorizationRepositoryImpl()).to(UserAuthorizationRepository.class);
    bind(new MyUserIdToUserNameTable()).to(UserIdToUserNameTable.class);
}

在此之后,我的资源类中的 userRepository 绑定正确,但是 UserAuthorizationRepositoryImpl 中的 userIdToUserNameTable 为空。

有人知道原因吗?提前谢谢!

【问题讨论】:

    标签: jersey jersey-2.0 hk2


    【解决方案1】:

    一方面,您似乎是在自己创建 UserAuthorizationRepositoryImpl,而不是让 hk2/Jersey 创建它。您可能想尝试一下:

    public class RepositoryBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(UserAuthorizationRepositoryImpl.class).to(UserAuthorizationRepository.class);
        bind(MyUserIdToUserNameTable.class).to(UserIdToUserNameTable.class);
    }
    

    这将允许 hk2/Jersey 创建类,并正确注入它们。

    【讨论】:

    • 这不起作用,因为现在 userRepository 也变为空
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多