【问题标题】:How can I inject a custom factory using hk2?如何使用 hk2 注入自定义工厂?
【发布时间】:2015-04-21 05:45:12
【问题描述】:

我很难使用球衣测试框架。

我有一个根资源。

@Path("sample")
public class SampleResource {

    @GET
    @Path("path")
    @Produces({MediaType.TEXT_PLAIN})
    public String readPath() {
        return String.valueOf(path);
    }

    @Inject
    private java.nio.file.Path path;
}

我准备了一个工厂提供path

public class SamplePathFactory implements Factory<Path> {

    @Override
    public Path provide() {
        try {
            return Files.createTempDirectory(null);
        } catch (final IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    @Override
    public void dispose(final Path instance) {
        try {
            Files.delete(instance);
        } catch (final IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }
}

还有一个活页夹。

public class SamplePathBinder extends AbstractBinder {

    @Override
    protected void configure() {
        bindFactory(SamplePathFactory.class).to(Path.class);
    }
}

最后,我的测试课。

public class SampleResourceTest extends ContainerPerClassTest {

    @Override
    protected Application configure() {
        final ResourceConfig resourceConfig
            = new ResourceConfig(SampleResource.class);
        resourceConfig.register(SamplePathBinder.class);
        return resourceConfig;
    }
}

当我尝试测试时,我得到了。

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=Path,parent=SampleResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1916953383)

我做错了什么?

【问题讨论】:

    标签: jersey jax-rs testng jersey-2.0 hk2


    【解决方案1】:

    您的AbstractBinders 应该注册为一个实例,而不是一个类。所以做出改变

    resourceConfig.register(new SamplePathBinder());
    

    它应该可以工作

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多