如何将依赖bean注入GridCacheStore实现?

时间:2014-07-07 08:56:03

标签: spring caching inversion-of-control gridgain

我的配置:

<bean parent="cache-template">
    <property name="name" value="yagoLabel" />
    <property name="cacheMode" value="PARTITIONED" />
    <property name="atomicityMode" value="TRANSACTIONAL" />
    <property name="distributionMode" value="PARTITIONED_ONLY" />
    <property name="backups" value="1" />
    <property name="store">
        <bean class="id.ac.itb.ee.lskk.lumen.yago.YagoLabelCacheStore" autowire="byType" init-method="init" />
    </property>
    <property name="writeBehindEnabled" value="true" />
    <property name="writeBehindFlushSize" value="102380" />
    <property name="writeBehindFlushFrequency" value="30000" />
    <property name="writeBehindBatchSize" value="10240" />
    <property name="swapEnabled" value="false" />
    <property name="evictionPolicy">
        <bean class="org.gridgain.grid.cache.eviction.lru.GridCacheLruEvictionPolicy">
            <property name="maxSize" value="102400" />
        </bean>
    </property>
</bean>

我按如下方式启动GridGain:

我的GridCacheStore实施:

public class YagoLabelCacheStore extends GridCacheStoreAdapter<String, YagoLabel> {

    private static final Logger log = LoggerFactory
        .getLogger(YagoLabelCacheStore.class);
    private DBCollection labelColl;

   @GridSpringResource(resourceName="mongoDb")
   private DB db;
   @Inject
   private GridGainSpring grid;

   @PostConstruct
   public void init() {
   log.info("Grid is {}", grid);
   labelColl = db.getCollection("label");
}

我按如下方式启动GridGain:

String entityId = "Muhammad";

try (AnnotationConfigApplicationContext appCtx 
          = new AnnotationConfigApplicationContext(LumenConfig.class)) {
    Grid grid = appCtx.getBean(Grid.class);
    GridCache<String, YagoLabel> labelCache = YagoLabel.cache(grid);
    log.info("Label for {}: {}", entityId, labelCache.get(entityId));
}

LumenConfig Spring配置包含一个名为DB的{​​{1}} bean。

但是这会抛出mongoDb,因为NullPointerException未正确注入。我尝试db仅用于测试,甚至@Inject GridGainSpring本身也没有注入。

我也尝试在GridGain Config XML中设置GridGainSpring但Spring抱怨找不到bean。

我的解决方法是将其放在<property name="db" ref="mongoDb"/>字段中,但这很糟糕:https://github.com/ceefour/lumen-kb/blob/b8445fbebd227fb7ac337c758a60badb7ecd3095/cli/src/main/java/id/ac/itb/ee/lskk/lumen/yago/YagoLabelCacheStore.java

1 个答案:

答案 0 :(得分:0)

方法是load the GridConfiguration using Spring, then pass it to GridGainSpring.start()

// "classpath:" is required, otherwise it won't be found in a WAR
@ImportResource("classpath:id/ac/itb/ee/lskk/lumen/core/lumen.gridgain.xml")
@Configuration
public static class GridGainConfig {

    @Inject
    private ApplicationContext appCtx;
    @Inject
    private GridConfiguration gridCfg;

    @Bean(destroyMethod="close")
    public Grid grid() throws GridException {
        return GridGainSpring.start(gridCfg, appCtx);
    }

}

: - )