Search code examples
cachingosgibundlespring-cacheapache-servicemix

Spring Abstraction Cache in OSGi Environment


I have problem making Spring Cache working in OSGi Environment. Maybe you can show me what i am missing.

I have configured Spring Cache successfully to work during tests like

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-test.xml"})
public class CacheDictTest {

@Autowired
Dictionary dictionary;

@Test
public void getDict5Times() {
    for (int i = 0; i < 5; i++) {
        System.out.println(dictionary.getSourceDomains());
    }
    Assert.assertTrue(true);
  }
}

The select is executed once and then i have 5 nice prints.

However I cannot make it work in a bundle

The Cacheable annotation seems to be ignored. Queries are performed everytime i call dictionary.getSourceDomains(). I use ServiceMix 5.3.0 as a container.

My configuration:

<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
        <set>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="dictionary"/>
        </set>
    </property>
</bean>

dictionary:

public class DictionaryImpl implements Dictionary {

private DictionaryDao repository;

public DictionaryDao getRepository() {
    return repository;
}

public void setRepository(DictionaryDao repository) {
    this.repository = repository;
}

@Override
public List<String> getSourceDomains() {
    List<DictEntry> entries = repository.getDictionary(DictTypeEnum.SOURCE_DOMAIN);
    List<String> domains = new ArrayList<>();
    for(DictEntry entry : entries) {
        domains.add(entry.getKey());
    }
    return domains;
  }



}

and dao

public class DictionaryDaoImpl extends BaseDaoImpl implements DictionaryDao {

private static final Logger LOG = LoggerFactory.getLogger(DictionaryDaoImpl.class);

@Override
@Cacheable(value="dictionary", key="#type")
public List<DictEntry> getDictionary(DictTypeEnum type) {
    LOG.info("Loading {}", type);
    Query q = getSession().createQuery("from DictEntry where type=:type");
    q.setParameter("type", new DictType(type.getTypeId()));
    List results = q.list();
    LOG.debug("Results {}", results);
    return results;
  }


}

What i tried

  • Moving @Cacheable annotation to DictionaryDao (interface), to DictionaryImpl or Dictionary (interface) - no effect.
  • Use different cache implementantion (ehcache instead of JDK ConcurrentMap-based Cache) - no effect

Solution

  • The problem was missing import of Cacheable annotation package in osgi manifest.

    org.springframework.cache.annotation
    

    Servicemix did not show any error for missing class, just let the service work ignoring Cacheable annotation.