使用FullyQualifiedAnnotationBeanNameGenerator时,@PreAuthorize中SpEL访问Bean问题
SpEL引用带点的全限定类名Bean解决方案
问题场景
我的Controller方法通过@PreAuthorize结合SpEL做权限校验,原本用默认Bean名称调用内部的hasPermission()方法:
@RestController @RequestMapping("/example") public class ExampleController { @GetMapping @PreAuthorize("@exampleController.hasPermission()") public String example() { return "hello"; } public boolean hasPermission() { return true; // 实际为复杂权限逻辑 } }
当配置Spring Boot使用FullyQualifiedAnnotationBeanNameGenerator作为Bean名称生成器后:
@SpringBootApplication(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
Bean名称变为全限定类名com.example.demo.ExampleController,此时直接在SpEL中写@com.example.demo.ExampleController.hasPermission()会报错,提示找不到名为com的Bean。
无效尝试
- 直接使用全限定类名:
@com.example.demo.ExampleController.hasPermission(),解析时把com当成Bean名称,导致错误 - 尝试XML风格表达式:
#{@'com.example.demo.ExampleController'.hasPermission()},表达式解析失败
有效解决方案
将全限定类名Bean用单引号包裹,正确的SpEL写法如下:
@PreAuthorize("@'com.example.demo.ExampleController'.hasPermission()")
该写法可以正确识别到目标Bean并调用权限方法,唯一需要注意的是IntelliJ会错误提示表达式无效,但实际运行完全正常。
内容的提问来源于stack exchange,提问作者mkczyk
相关产品推荐
相关产品推荐

