Spring Data Rest 自定义参数解析器

Spring Data Rest custom argument Resolver

所以我正在尝试将自定义参数解析器添加到我的 Spring-Data-Rest 项目中。 我正在开发一个多租户应用程序,需要根据用户租户 ID 过滤数据。 所以我写了一个简单的注释和 ArgumentResolver 来查询我的租户存储库并在一些需要的方法上注入一个租户对象作为参数:

处理程序:

@AllArgsConstructor
public class TenantInjector implements HandlerMethodArgumentResolver {

    private final TenantStore tenantStore;

    private final TenantRepository tenantRepository;


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if(! methodParameter.hasParameterAnnotation(InjectTenant.class)) {
            return false;
        }
        return true;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        return tenantRepository.findById(tenantStore.getId()).get();
    }

}

此处理程序查询 tenantRepository 以通过其 Id 查找当前租户,该 Id 在解析传入请求安全令牌时设置。

要注册处理程序,我执行以下操作:

@Configuration
public class DispatcherContext implements WebMvcConfigurer  {

    private final TenantStore tenantStore;


    private final TenantRepository tenantRepository;

    @Autowired
    public DispatcherContext(TenantStore tenantStore, TenantRepository tenantRepository) {
        this.tenantStore = tenantStore;
        this.tenantRepository= tenantRepository;
    }

    @Override
    public void addArgumentResolvers(
            List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new TenantInjector(tenantStore, tenantRepository));
    }
}

只要相应的控制器用@Controller 或@RestController 注释,这就很好用

由于@RepositoryRestController 有其他上下文,此配置将被忽略。如何将相同的 ArgumentResolver 添加到 Spring-Data-Rest 配置?

切换注释可能是一种选择,但我宁愿坚持使用这种方法,因为链接是由 spring-data-rest 生成的。

有没有人偶然发现这个?

您的问题可能是您在 WebMvcConfigurer 中注册了自定义参数解析器。 Spring Data Rest 似乎在不同的上下文中工作,因此您必须在 RepositoryRestMvcConfiguration.

中注册您的自定义参数解析器
@Configuration
public class RepositoryConfiguration extends RepositoryRestMvcConfiguration {

    public RepositoryConfiguration(ApplicationContext context, ObjectFactory<ConversionService> conversionService)
    {
        super(context, conversionService);
    }

    @Override
    protected List<HandlerMethodArgumentResolver> defaultMethodArgumentResolvers()
    {
        List<HandlerMethodArgumentResolver> resolvers = 
            new ArrayList<>(super.defaultMethodArgumentResolvers());
        resolvers.add(new TenantInjector(tenantStore, tenantRepository));
        return resolvers;
    }
}

回答灵感来自:https://github.com/tkaczmarzyk/specification-arg-resolver/issues/6#issuecomment-111952898