Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable cache for a method inside dynamic bean

I am creating 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 method getValue() executes its body every time. Spring doesn't cache the value as expected. Any suggestions?

like image 382
sag Avatar asked May 09 '16 13:05

sag


1 Answers

I think the problem is that when spring register a bean with annotation, it is then post-processed by a bean post processor that will manage @Cacheable

When you register it manually, the post-processing might not get done.

Can't verify it for the moment, but that's where I'll look first.

Hope this help.

like image 91
nhu Avatar answered Sep 28 '22 02:09

nhu