Spring-MVC + Spring-websocket + @Cacheable不工作
问题描述:
我有一个关于Spring-MVC和Spring-websockets的项目,我尝试在我的服务层上插入缓存。这是我的配置:Spring-MVC + Spring-websocket + @Cacheable不工作
@Configuration
@ComponentScan(basePackages = {
"com.example"
})
@PropertySource("classpath:/configuration.properties")
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableCaching
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Bean
public EhCacheManagerFactoryBean ehcache() {
EhCacheManagerFactoryBean ehCache = new EhCacheManagerFactoryBean();
ehCache.setConfigLocation(new ClassPathResource("ehcache.xml"));
ehCache.setShared(true);
return ehCache;
}
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehcache().getObject());
}
//...different settings by mvc
}
和我的WebSocket配置:
@Configuration
@EnableAsync
@EnableWebSocket
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue/", "/topic/");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/locations").withSockJS();
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(4).maxPoolSize(10);
}
}
我想用@Cacheable
诠释我的服务层上:
@Service
public class StoreServiceImpl implements StoreService {
private static final Log logger = LogFactory.getLog(StoreServiceImpl.class);
@Autowired
private StoreRepository storeRepository;
@Override
@Cacheable("stores")
public Store findById(String storeId) {
return storeRepository.findById(storeId);
}
//... others methods
}
,但如果我已经包含注释@EnableWebSocketMessageBroker
然后缓存不起作用,因为aop拦截器不使用它,所以如果我还没有包含
然后缓存和AOP拦截器运作良好。@EnableWebSocketMessageBroker
上的WebSocket的文档,我发现这样的信息:
在某些情况下,控制器可能需要在运行时,AOP代理 装饰。例如,如果您选择在控制器上直接使用
@Transactional
注释。在这种情况下,对于 控制器,我们建议使用基于类的代理。 这通常是控制器的默认选择。然而,如果一个 控制器必须实现一个非弹簧上下文回调的接口(例如InitializingBean
,* Aware等),您可能需要 显式配置基于类的代理。例如与<tx:annotation-driven />
,更改为<tx:annotation-driven proxy-target-class="true" />
我尝试使用@EnableCaching(proxyTargetClass = true)
,但它并没有帮助。
有没有人遇到过这个问题?
答
我决定这个问题: 我在@EnableAsync(mode = AdviceMode.ASPECTJ)中改变了模式,它工作。 我认为这取决于订单的初始化BeanPostProcessors
您使用的是哪个Spring版本? –
版本4.2.4 @BrianClozel –
然后这可能与[SPR-14030](https://jira.spring.io/browse/SPR-14030)链接。 Spring 4.1.x有相同的行为吗? –