You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加@PreAuthorize注解后Autowired注入的DataSource报NullPointerException

问题原因及解决方案

核心原因

你遇到的空指针问题根源在于private方法无法被Spring AOP代理拦截,而@PreAuthorize注解是通过Spring AOP实现方法级权限控制的。当你给private的createParent方法添加@PreAuthorize后,Spring无法对该方法生成有效的代理增强,导致调用该方法时,实际使用的对象没有经过Spring的依赖注入流程,从而dataSource等依赖项为null。

另外,Spring默认只会对public方法创建AOP代理,非public方法的注解逻辑不会生效,同时还会引发依赖注入异常。

解决方案

  1. 修改方法访问修饰符为public
    将createParent方法的private改为public,让Spring AOP能够正常拦截并处理@PreAuthorize注解:

    @PreAuthorize("hasRole('COORDINATOR')")
    @PostMapping("/create")
    public String createParent(final Parent inParent, HttpServletResponse response) {
        // 方法逻辑
    }
    
  2. 确保方法级安全已启用
    检查你的Spring Security配置类,是否添加了@EnableGlobalMethodSecurity(prePostEnabled = true)注解,开启预/post方法级安全支持:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        // 配置逻辑
    }
    

验证

修改后重新启动应用,调用/Parent/create接口,此时Spring会正常生成代理对象,依赖注入的dataSource不会再为null,同时@PreAuthorize的权限控制逻辑也会生效。

内容的提问来源于stack exchange,提问作者tcelvis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:55:08