How to enable cache for a method inside a dynamic bean

I create a dynamic bean using "AutowireCapableBeanFactory" as follows

RegisterFoo.java

@Configuration public class registerFoo { @Autowired ApplicationContext appcontext; AutowireCapableBeanFactory bf; @PostConstruct public void registerFoo() { bf = appContext.getAutowireCapableBeanFactory(); RootBeanDefinition def = new RootBeanDefinition(Foo.class); ((DefaultListableBeanFactory)bf).registerBean("foo", def); } } 

RegisterBar.java

 @Configuration public class registerBar { @Autowired ApplicationContext appcontext; AutowireCapableBeanFactory bf; @PostConstruct public void registerFoo() { bf = appContext.getAutowireCapableBeanFactory(); RootBeanDefinition def = new RootBeanDefinition(Bar.class); Foo foo = (Foo) appContext.getBean("foo"); ConstructorArgumentValues cav = new ConstructorArgumentValues(); cav.add(0, foo.getValue()); def.setArgumentValues(cav); ((DefaultListableBeanFactory)bf).registerBean("bar", def); } } 

Foo.class

 public class Foo { @Cacheable public String getValue() { // return value } } 

The getValue () method executes its body every time. Spring does not cache the value as expected. Any suggestions?

+7
spring-boot caching guava
source share
1 answer

I think the problem is that when spring registers the bean with annotation, it is then processed by the bean post processor that will control @Cacheable

When you register it manually, post processing may not complete.

It is not possible to check it at the moment, but here is where I will look first.

I hope for this help.

+1
source share

All Articles