将@Resource导入我的Guice模块

时间:2013-03-06 15:15:30

标签: jboss7.x guice infinispan

我已经看到了各种各样的点点滴滴,但是我要么接近这个错误,要么对我对Guice的理解有点短暂。我正在尝试修改/扩展此cache4guice Infinispan Module,以便它可以访问JBoss嵌入式模块,并最终在所选缓存容器中命名缓存。

因此,我们的standalone.xml包含以下内容:

<cache-container name="InfinispanCacheModule" default-cache="cache1" jndi-name="java:jboss/infinispan/container/mycachecontainer>
<local-cache name="cache1">
    <eviction strategy="LRU" max-entries="1000"/>
    <expiration max-idle="50000"/>
    <file-store preload="true" passivation="true" purge="false"/>
</local-cache>
<local-cache name="cache2">
    <eviction strategy="LRU" max-entries="500"/>
    <expiration max-idle="20000"/>
    <file-store preload="true" passivation="false" purge="false"/>
</local-cache>

我修改了@Cached注释以允许可选地包含cachedName参数。你可以将它用于默认缓存:

@Cached
public someMethod(String someArg) {...}

这用于访问cache2及更高版本......

@Cached(cacheName="cache2")
public someOtherMethod(String someArg) {...}

我发现的唯一允许我访问内容的例子就是使用jndi资源,例如在本页中 - ttp://my.safaribooksonline.com/book/web -Development / 9781590599976 /吉斯-食谱/ integrating_jndi

这导致我尝试这样的事情:

public class InfinispanCacheModule extends CacheModule {
...
    @Override
    protected void configure() {
        // bind naming context to the default InitialContext
        bind(Context.class).to(InitialContext.class);

        bind(CacheContainer.class).toProvider(JndiIntegration.fromJndi(CacheContainer.class, "java:jboss/infinispan/container/mycachecontainer"));

        bindInterceptor(Matchers.any(), Matchers.annotatedWith(Cached.class), new CacheInterceptor(this));        
    }

此外,从这里和其他地方的帖子来看,似乎我可能想要使用@Provides方法 - 沿着这些方向: https://stackoverflow.com/a/8999548/880884 Guice: is it possible to inject modules?

所以,现在我们进入细节,如果我们看一下原始的InfinispanModule,我的想法是在模块创建时传入CacheManager,或者以某种方式在模块中创建一个。

public class MyGuiceFactory {
private static final Injector inj = Guice.createInjector(
new SomeGuiceModule(), 
new InfinispanCacheModule(---- what goes here? -----)
);
public static Injector getInjector() {
    return inj;
}
}

类似的问题: Spring, Infinispan and JBoss 7 integration

1 个答案:

答案 0 :(得分:1)

为了实现这一点,我只使用了普通的上下文和查找。我在Guice Factory中放置了以下方法,然后通过新的构造函数将CacheContainer传递给InfinispanCacheModule。

public static CacheContainer getCacheContainer() {
    org.infinispan.manager.CacheContainer container = null;
    try {
        Context ctx = new InitialContext();
        container = (CacheContainer) ctx
                .lookup("java:jboss/infinispan/container/mycache");
    } catch (NamingException e) {
        e.getCause();
    }
    return container;
}

从那里我可以在Injector中使用'cacheName'注释参数,然后返回到InfinispanCacheModule的getCache(String cacheName)方法。如果你想让我分享更多的代码,我会发布更多细节。