@Inject在Singleton中不起作用,但在API类中起作用

时间:2019-03-22 19:51:18

标签: java dependency-injection jersey singleton

我正在Jetty API中设置身份验证。而且我想使用依赖注入将具有数据库功能的类注入到该类中,以根据数据库检查提供的令牌。

我已经在我的API类中使用了依赖注入:

@Path("/account")
@Api(value = "/account", description = "Web Service for accounts")
public class AccountService {

    @Inject
    private IAccountRepo accountRepo;
}

为此,我创建了一个将实际类绑定到接口的类。

public class RepositoryBinder extends AbstractBinder {

    @Override
    protected void configure() {
        bind(MovieRepo.class).to(IMovieRepo.class);
        bind(AccountRepo.class).to(IAccountRepo.class);
    }
}

我这样注册它:

ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.packages(
        MovieService.class.getPackage().getName(),
        AccountService.class.getPackage().getName(),
        ApiListingResource.class.getPackage().getName()
);
resourceConfig.register(new RepositoryBinder());
resourceConfig.register(new AuthenticationFilter());
resourceConfig.register(ObjectMapperContextResolver.class);

但是当我尝试在TokenValidator类中使用它时,accountRepo始终为空。

我的TokenValidator看起来像这样:

@Singleton
public class TokenValidator implements ITokenValidator {

    @Inject
    private IAccountRepo accountRepo;

    private static ITokenValidator instance = null;

    private TokenValidator() {
    }

    public static ITokenValidator getInstance() {
        if (instance == null) {
            instance = new TokenValidator();
        }
        return instance;
    }

    //Some token validation logic here
}

我希望@Inject可以立即工作,但不能。我已经尝试过很多方法,例如以与注册API类相同的方式注册TokenValidator,但到目前为止没有任何效果。

0 个答案:

没有答案