我们可以在XMl文件中替换Springframework注释(@ CacheConfig,@ Cacheable,@ CachePut)吗?

时间:2019-03-21 08:53:53

标签: spring spring-cache spring-framework-beans

我正在用Spring Cache机制实现一个模块。该模块是通用模块,可以缓存不同类型的实体。因此,我不想更改Java代码并希望用户相应地配置applicationcontext.xml文件。他可以将不同类型的实体的名称放在applicationcontext.xml中,并且代码应该起作用。例如-

<context:annotation-config/>
<cache:annotation-driven cache-manager="cacheManager"/>
<context:component-scan base-package="com.nokia.oss.sure.adapter"/>

<bean id="NetworkEntityService" class="com.nokia.oss.sure.adapter.cache.NetworkEntityServiceImpl"/>

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
        <set>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" name="NetworkEntity"/>
        </set>
    </property>
</bean>

他可以将NetworkEntity更改为ServiceEntity,等等。

因此,在Java代码中,我需要提及-

@CacheConfig(cacheNames={"NetworkEntity"})

或者我可以为每种方法都放同样的东西-

@CachePut(cacheNames="NetworkEntity", key="#entity.sureName")
public Entity addEntity(Entity entity) {
    return entity;
}

但是正如我之前所说,我不想在Java代码中放入缓存名称“ NetworkEntity”,而是希望在applicationcontext.xml文件中放入相同的名称。可能吗?

此外,可以省略Java文件中的所有注释吗?如果我只使用AbstractApplicationContext context = new GenericXmlApplicationContext("applicationContext.xml");,是否有可能在applicationContext.xml文件中提及要在其中应用@Cacheable注释的方法有哪些,例如

我搜索了很多东西,在任何地方都找不到。

谢谢 尼尔玛利亚

1 个答案:

答案 0 :(得分:0)

我找到了答案。我们可以将以下内容放入applicationContext.xml-

<!-- define caching behavior -->
    <cache:advice id="cacheAdviceInterface" cache-manager="cacheManager">
        <cache:caching cache="NetworkEntity">
            <cache:cacheable method="getEntity"/>
            <cache:cache-put method="putEntity"/>
        </cache:caching>
    </cache:advice>

在这种情况下,我们不需要在Java文件中放置@ CacheConfig,@ CachePut等注释。

相关问题