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

Springboot中AspectJ切面Autowired字段为空的解决办法

Spring Boot中AspectJ切面@Autowired注入为null的解决方案

问题原因

原生AspectJ的切面实例由AspectJ Weaver创建,而非Spring容器管理,因此Spring无法自动为其注入@Autowired标记的依赖,导致字段为null。

解决方案

方案一:改用Spring AOP(推荐,适用于大多数场景)

如果切面仅需拦截Spring容器中的Bean方法,直接将切面类交给Spring管理即可:

  1. 给切面类添加@Component注解,让Spring将其识别为Bean
  2. 主启动类或配置类无需额外添加@EnableAspectJAutoProxy(Spring Boot默认已启用)

修改后的切面代码:

@Aspect
@Component
public class AuthorizationAspect {

    @Autowired
    private UserService userService;

    @Around("execution(* some.controller.Method(..))")
    public ResponseEntity<?> checkIfAdmin(ProceedingJoinPoint joinPoint) throws Throwable {
        // 正常使用userService处理权限逻辑
        return (ResponseEntity<?>) joinPoint.proceed();
    }
}

方案二:让Spring管理原生AspectJ切面实例(适用于必须使用原生AspectJ的场景)

若需要拦截非Spring Bean或构造器等Spring AOP不支持的场景,需将AspectJ生成的切面实例交给Spring管理:

  1. 创建Spring配置类,通过AspectJ的aspectOf()方法获取切面实例并注册为Bean
  2. 确保AspectJ Weaver配置正确

配置类代码:

@Configuration
public class AspectConfig {
    @Bean
    public AuthorizationAspect authorizationAspect() {
        // 获取AspectJ生成的切面实例,交给Spring管理以实现依赖注入
        return AuthorizationAspect.aspectOf();
    }
}

添加AspectJ依赖(pom.xml):

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.20</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.20</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

开启加载时织入(application.properties):

spring.aop.proxy-target-class=true
spring.aspectj.weaver.enabled=true

方案三:手动静态注入(应急方案,不推荐)

若以上方案无法快速生效,可通过静态方法手动注入依赖:
切面类修改:

@Aspect
public class AuthorizationAspect {

    private static UserService userService;

    public static void setUserService(UserService service) {
        userService = service;
    }

    @Around("execution(* some.controller.Method(..))")
    public ResponseEntity<?> checkIfAdmin(ProceedingJoinPoint joinPoint) throws Throwable {
        // 使用静态userService处理逻辑
        return (ResponseEntity<?>) joinPoint.proceed();
    }
}

配置类添加初始化逻辑:

@Configuration
public class AspectConfig {
    @Autowired
    private UserService userService;

    @PostConstruct
    public void initAspectDependency() {
        AuthorizationAspect.setUserService(userService);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:23:19