Spring验证和Spring缓存代理顺序不起作用

时间:2016-05-16 00:39:23

标签: java spring ehcache spring-cache spring-validator

当我集成Spring缓存(使用EHCache)和Spring验证时,代理顺序没有正确设置。

我希望在处理缓存注释(在本例中为CacheEvict)之前处理验证注释。

我的配置类:

@EnableCaching( order = Ordered.LOWEST_PRECEDENCE )
@Configuration
public class CommonConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() throws IOException {

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor( LocalValidatorFactoryBean validator ) {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator( validator );
        methodValidationPostProcessor.setOrder( Ordered.LOWEST_PRECEDENCE- 1 );
        return methodValidationPostProcessor;
    }

    @Bean
    public EhCacheCacheManager cacheManager() {
        EhCacheCacheManager cacheManager = new EhCacheCacheManager();
        cacheManager.setCacheManager( ehCacheManager().getObject() );
        return cacheManager;
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheManager() {
        EhCacheManagerFactoryBean ehcache = new EhCacheManagerFactoryBean();
        ehcache.setConfigLocation( new ClassPathResource( "ehcache.xml" ) );
        return ehcache;
    }

}

我的相关依赖项:

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.2</version>
        </dependency>

带有问题的接口和实现类:

@Validated
public interface MyRepository {

    public void update(@NotNull MyEntity entity);

}


@Repository
public class MyRepositoryImpl implements MyRepository {

    @CacheEvict(cacheNames = {"entityCache"});
    public void update(MyEntity entity);
}

可以看出,我已将MethodValidationPostProcessor的订单设置为Orderer.LOWEST_PRECEDENCE- 1,并将订单设置为Ordered.LOWEST_PRECEDENCE(在@EnacbleCaching中)。

这是设置代理订单的正确方法吗?

问题可能与在接口中使用验证注释和在实现中缓存注释有关吗?

1 个答案:

答案 0 :(得分:0)

我根据提供的建议hereherehere(基于非基于xml的配置)设法解决了这个问题。

主要观点是MethodValidationPostProcessor的顺序只是后处理器的顺序,而不是我们所追求的建议之一。

请参阅commit以了解解决此缓存/验证问题所需的更改。