Custom default headers for REST API only using Spring Data REST

后端 未结 3 2164
我寻月下人不归
我寻月下人不归 2020-12-09 14:16

I have a use case where my application hosts REST API and web application and we need to add custom header to REST APIs only. REST APIs are enabled through Spring Data REST.

3条回答
  •  余生分开走
    2020-12-09 14:35

    Finally I managed to make the setup of custom interceptor working also on spring-data-rest 2.4.1.RELEASE.

    @Configuration
    public class RestMvcConfig extends RepositoryRestMvcConfiguration {
    
        @Autowired UserInterceptor userInterceptor;
    
        @Autowired ApplicationContext applicationContext;
    
        @Override
        public DelegatingHandlerMapping restHandlerMapping() {
    
            RepositoryRestHandlerMapping repositoryMapping = new RepositoryRestHandlerMapping(resourceMappings(), config());
            repositoryMapping.setInterceptors(new Object[] { userInterceptor }); // FIXME: not nice way of defining interceptors
            repositoryMapping.setJpaHelper(jpaHelper());
            repositoryMapping.setApplicationContext(applicationContext);
            repositoryMapping.afterPropertiesSet();
    
            BasePathAwareHandlerMapping basePathMapping = new BasePathAwareHandlerMapping(config());
            basePathMapping.setApplicationContext(applicationContext);
            basePathMapping.afterPropertiesSet();
    
            List mappings = new ArrayList();
            mappings.add(basePathMapping);
            mappings.add(repositoryMapping);
    
            return new DelegatingHandlerMapping(mappings);  
        }
    
    }
    

    I had to override the restHandlerMapping method, copy-paste it's content and add a line repositoryMapping.setInterceptors for adding custom interceptor, in my case the UserInterceptor.

    Is there any better way?

提交回复
热议问题