问题
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";
}
}
I noticed the injected validator is always null in the initBinder
method , the logger is even null (and throws NPE) , this is weird.
If I totally remove the @InitBinder initBinder()
method , the myValidator
is available (not null) again in each method.
After eliminating many factors , I found the culprit is the @PreAuthorize("hasAuthority('USER')")
. After removing this @PreAuthorize
, everything works fine.
Is it a bug ? Does something conflicts with SpringSecurity and SpringValidation and SpringMVC ?
How to fix it ?
environments :
<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>
Thanks in advanced.
回答1:
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.
来源:https://stackoverflow.com/questions/33174428/preauthorize-controller-invalidates-inject-in-initbinder