2014-11-21 93 views
5

在以下設置中,TimingInterceptor和CORSHeaders攔截器在所有URL請求上執行,除/ resources/** URL之外。如何使攔截器對ResourceHttpRequestHandler提供的/ resources/** URL起作用?Spring MVC攔截器不會執行資源處理程序URL

@EnableWebMvc //equivalent to mvc:annotation-driven 
@Configuration 
@PropertySource("classpath:configuration.properties") 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Inject 
    private TimingInterceptor timingInterceptor; 

    @Inject 
    private CORSHeaders corsHeaders; 

    // equivalent to mvc:resources 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 

    } 

    // equivalent to mvc:interceptors 
    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
     registry.addInterceptor(timingInterceptor).addPathPatterns("/**"); 
     registry.addInterceptor(corsHeaders).addPathPatterns("/**"); 
    } 

} 

回答

2

更新:由於Spring框架5.0.1(和SPR-16034)的,攔截器會自動在ResourceHttpRequestHandler默認情況下映射。

我認爲配置的攔截器不是在資源處理器上映射的,而是在處理@RequestMapping請求的映射器上映射的。

也許試試這個呢?

@EnableWebMvc //equivalent to mvc:annotation-driven 
@Configuration 
@PropertySource("classpath:configuration.properties") 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Inject 
    private TimingInterceptor timingInterceptor; 

    @Inject 
    private CORSHeaders corsHeaders; 

    // equivalent to mvc:resources 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 

    } 

    @Bean 
    public MappedInterceptor timingInterceptor() { 
     return new MappedInterceptor(new String[] { "/**" }, timingInterceptor); 
    } 

    @Bean 
    public MappedInterceptor corsHeaders() { 
     return new MappedInterceptor(new String[] { "/**" }, corsHeaders); 
    } 

} 

這應該更好地記錄在SPR-10655

+0

是的我認爲你是對的。我試着按照你的建議添加一個MappedInterceptor,但是這個方法沒有被調用,攔截器也沒有被添加到上下文中。 – tukushan 2014-11-25 10:41:42

+1

我已經爲此創建了一個簡單的示例:https://github.com/spring-projects/spring-framework-issues/tree/master/SPR-10655 - 您可以看看它嗎?如果你想出一個帶有可能bug的repro項目,只需在http://jira.spring.io上打開一個JIRA問題。 – 2014-12-31 15:57:36

+0

@BrianClozel使用'@EnableWebMvc'和'WebMvcConfigurerAdapter'合在一起是明智的嗎? [document](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration)另有說明。或者我錯過了什麼? – 2016-11-02 06:16:50

0

我從來沒有嘗試過使用Spring攔截器來提供資源。攔截器的功能是在控制器之前以及控制器和視圖之間具有掛鉤

要在資源周圍添加預處理或後處理,最好使用過濾器。