问题描述
在一个简单的控制器中:
In a simple controller :
@PreAuthorize("hasAuthority('USER')")
@Controller
@RequestMapping("/test")
public class TestController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Inject
private MyValidator myValidator;
@InitBinder("myObj")
private void initBinder(WebDataBinder binder) {
logger.info("myValidator = {}", myValidator);
binder.initDirectFieldAccess();
binder.setValidator(myValidator);
}
@RequestMapping(value = "/doPost", method = RequestMethod.POST)
public String doPost(MyObj myObj , BindingResult br ) throws IOException {
logger.info("myObj = {} , bindingResult = {}" , myObj , br);
return "redirect:/test/form";
}
}
我注意到在initBinder
方法中注入的验证器始终为null,记录器甚至为null(并抛出NPE),这很奇怪.
I noticed the injected validator is always null in the initBinder
method , the logger is even null (and throws NPE) , this is weird.
如果我完全删除了@InitBinder initBinder()
方法,则每种方法中的myValidator
都将再次可用(不为null).
If I totally remove the @InitBinder initBinder()
method , the myValidator
is available (not null) again in each method.
消除许多因素后,我发现罪魁祸首是@PreAuthorize("hasAuthority('USER')")
.删除此@PreAuthorize
后,一切正常.
After eliminating many factors , I found the culprit is the @PreAuthorize("hasAuthority('USER')")
. After removing this @PreAuthorize
, everything works fine.
这是一个错误吗?与SpringSecurity和SpringValidation和SpringMVC有冲突吗?
Is it a bug ? Does something conflicts with SpringSecurity and SpringValidation and SpringMVC ?
如何修复?
环境:
<spring.version>4.2.1.RELEASE</spring.version>
<springboot.version>1.3.0.M5</springboot.version>
<spring-security.version>4.0.2.RELEASE</spring-security.version>
非常感谢.
推荐答案
最简单的解决方案是为myValidator
创建一个setter方法.然后在应用初始化时调用此setter.对所有已被@PreAuthorize标记取消的注射剂执行此操作.
The easiest solution was to create a setter method for myValidator
. this setter is then called when the app initializes. Do this for all the injectables that are being nullified by @PreAuthorize tags.
这篇关于@PreAuthorize控制器会使@InitBinder中的@Inject无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!