Skip to content

Programmatic creation of caching proxies using CacheProxyFactoryBean does not work [SPR-16295] #20842

@spring-projects-issues

Description

@spring-projects-issues

John Blum opened SPR-16295 and commented

When a user attempts to create caching proxies using the o.s.cache.interceptor.CacheProxyFactoryBean, this fails to work.

A user might want to use the CacheProxyFactoryBean to introduce caching behavior and logic to classes from a 3rd party library. This recently came up in a StackOverflow post. Please read the post and the answers (especially this one) for further details.

Ideally, a user would be able to add caching behavior to any class, programmatically (not declaratively) using...

@Bean
CacheProxyFactoryBean someBean() {

    CacheProxyFactoryBean factoryBean = new CacheProxyFactoryBean();

    factoryBean.setCacheOperationSources(...);
    factoryBean.setTarget(new ThirdPartyClass());

    return factoryBean;
}

Unfortunately, this does not work because the internal CacheInterceptor's afterSingletonesInitialized() method never gets called, thereby setting the initialized bit and therefore allowing the caching behavior/logic to be evaluated. As result, the target object's original operation is always invoked, forgoing any caching behavior, making any caching proxy configuration useless.

This can be fixed by having CacheProxyFactoryBean implement the SmartInitializingSingleton interface along with BeanFactoryAware and delegating said operations to the internal CacheInterceptor.

See Pull Request for fix.


Affects: 4.3.13, 5.0.2

Reference URL: https://stackoverflow.com/questions/47665485/how-can-i-manually-add-a-spring-cacheinterceptor-using-java-config

Issue Links:

Referenced from: pull request #1624, and commits b160f93, d53ede9

Backported to: 4.3.14

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions