启动时修改@RequestMappings

2024-05-12

是否可以更改@RequestMapping启动时的值?

基本上我想要的是创建一个注释@Api(Api.Version.V1)这意味着请求映射应该修改为/api/dogs to /api/v1/dogs。我想在类级别(适用于所有)和方法级别(重新使用早期版本的控制器并修改它)上执行此操作。

我可以对此进行硬编码,但这会留下很多字符串需要处理,而且它并不像我想要的那么干净。

那么是否可以(使用 bpp 或类似的东西)在启动期间更改请求映射?创建 bean 后,我不想/不需要修改它们。

我也一直在研究RequestCondition但这似乎具有更动态的性质,我不确定它在这种情况下对我有帮助。

另一个问题,我希望能够使用相同的请求映射注释两个类(然后让注释重写它),并且我很确定这需要在初始上下文加载时完成(这样我们就不会重复)映射等)。

任何正确方向的指示将不胜感激。

Edit:

几乎可以正常工作了,我正在使用自定义的RequestMappingHandlerMapping并重写该方法getMappingForMethod,它允许我获取注释(类型和方法上)并返回修改后的RequestMappingInfo添加了路径。

即使我删除所有旧映射并仅返回,仍然存在一个问题/api/v1/dogs旧映射到/api/dogs仍然有效。是否也可以以某种方式删除此映射?

代码在这里,如果有人感兴趣的话。

@Component
public class CustomRequestMappingHandlerMapping
    extends RequestMappingHandlerMapping
{
    @Override
    protected RequestMappingInfo getMappingForMethod( Method method, Class<?> handlerType )
    {
        RequestMappingInfo info = super.getMappingForMethod( method, handlerType );

        ApiVersion methodApiVersion = AnnotationUtils.findAnnotation( method, ApiVersion.class );
        ApiVersion typeApiVersion = AnnotationUtils.findAnnotation( handlerType, ApiVersion.class );

        if ( typeApiVersion == null )
        {
            return info;
        }

        Set<String> oldPatterns = info.getPatternsCondition().getPatterns();
        Set<String> patterns = new HashSet<>();

        for ( String p : oldPatterns )
        {
            for ( int v = 0; v < typeApiVersion.value().length; v++ )
            {
                ApiVersion.Version version = typeApiVersion.value()[v];

                if ( !p.startsWith( version.getValue() ) )
                {
                    if ( p.startsWith( "/" ) ) patterns.add( "/" + version.getValue() + p );
                    else patterns.add( "/" + version.getValue() + "/" + p );
                }
                else
                {
                    patterns.add( p );
                }
            }
        }

        PatternsRequestCondition patternsRequestCondition = new PatternsRequestCondition(
            patterns.toArray( new String[]{} ), null, null, true, true, null );

        RequestMappingInfo mappingInfo = new RequestMappingInfo(
            null, patternsRequestCondition, info.getMethodsCondition(), info.getParamsCondition(), info.getHeadersCondition(), info.getConsumesCondition(),
            info.getProducesCondition(), info.getCustomCondition()
        );

        return mappingInfo;
    }
}

您可以通过实现来动态添加 requestMappingsHandlerMapping接口或扩展AbstractUrlHandlerMapping.

这个想法是创建您自己的自定义处理程序映射,而不是使用默认实现,例如SimpleUrlHandlerMapping,DefaultAnnotationHandlerMapping etc

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

启动时修改@RequestMappings 的相关文章

随机推荐