【问题标题】:How to enable cache for a method inside dynamic bean如何为动态 bean 中的方法启用缓存
【发布时间】:2016-05-09 13:48:19
【问题描述】:

我正在使用“AutowireCapableBeanFactory”创建一个动态bean,如下所示

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
    }
}

getValue() 方法每次都会执行它的主体。 Spring 没有按预期缓存该值。有什么建议吗?

【问题讨论】:

  • 非常感谢这里的任何输入。
  • 您的应用程序中是否还有其他地方可以使用缓存?除了动态bean?
  • @Patrick - 是的,它适用于普通 bean。即使用 @Bean 注释创建的 bean。
  • 您是如何启用缓存注释的?发布的配置类上没有 @EnableCaching。
  • @thirstycrow 我们的@SpringBootApplication 类中有@EnableCaching

标签: caching spring-boot guava


【解决方案1】:

我认为问题在于,当 spring 注册一个带有注解的 bean 时,它会被一个将管理 @Cacheable 的 bean 后处理器进行后处理

当您手动注册时,后处理可能无法完成。

暂时无法验证,但这是我首先要看的地方。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-08
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多