gpt4 book ai didi

Spring HandlerMethodArgumentResolver 未执行

转载 作者:IT老高 更新时间:2023-10-28 13:48:21 35 4
gpt4 key购买 nike

我正在使用 Spring MVC 3.2.2

我已经定义了一个像这样的自定义 HandlerMethodArgumentResolver 类

public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

public CurrentUserArgumentResolver() {
System.out.println("Ready");
}

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(CurrentUser.class);
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

Principal principal = webRequest.getUserPrincipal();
System.out.println("*** Principal ***: " + principal);
return principal;
}
}

并将以下内容添加到我的 app-servlet.xml

<mvc:annotation-driven>
<mvc:argument-resolvers>
<beans:bean class="my.package.CurrentUserArgumentResolver" lazy-init="false"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>

并为 CurrentUser 创建了注解

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {

}

当我启动应用程序时,会构造类,因为我可以看到日志消息“就绪”,但是当我这样注释 Controller 方法时解析器不会执行(在具有 @Controller 注释的类中)

@RequestMapping(method = RequestMethod.POST, value = "/update")
public ModelAndView update(@RequestParam MultipartFile background, @CurrentUser Principal principal) {
...
}

如果我在 CurrentUserArgumentResolver 类中的任一方法上设置断点,都不起作用。所以不确定我错过了什么?

最佳答案

如果有人想要将自定义处理程序优先于 spring 添加的默认处理程序,这里有一个片段可以为我完成,我在 @Configuration 文件中执行此操作

private @Inject RequestMappingHandlerAdapter adapter;

@PostConstruct
public void prioritizeCustomArgumentMethodHandlers () {
List<HandlerMethodArgumentResolver> argumentResolvers =
new ArrayList<> (adapter.getArgumentResolvers ());
List<HandlerMethodArgumentResolver> customResolvers =
adapter.getCustomArgumentResolvers ();
argumentResolvers.removeAll (customResolvers);
argumentResolvers.addAll (0, customResolvers);
adapter.setArgumentResolvers (argumentResolvers);
}

关于Spring HandlerMethodArgumentResolver 未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17331448/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com