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

SpringBoot整合stateless4j时Autowired注入CTU1出现空指针问题

SpringBoot中@Autowired注入CTU1为null的解决方案

问题场景

在SpringBoot项目中,继承自ConditionTest模块CTU类的CTU1添加了@Component和@Async("myExecutor")注解;Commandline类实现CommandLineRunner并添加@Component、@Async("myExecutor")注解,使用@Autowired注入CTU1时触发空指针异常。

原因分析

  • 当Commandline类添加@Async注解后,Spring会为其生成代理对象,run方法会被异步执行。此时Spring上下文可能尚未完成所有Bean的初始化注入,导致ctu1未被实例化注入,从而抛出NullPointerException。
  • Spring默认对实现接口的类使用JDK动态代理,代理机制可能导致目标对象的依赖注入字段无法被正确传递到代理对象中。

解决方案

方案一:移除Commandline类的@Async注解(推荐)

让CommandLineRunner的run方法同步执行,此时Spring上下文已完全初始化,所有Bean都完成注入:

@Component
@Slf4j
class Commandline implements CommandLineRunner{

    @Autowired
    private CTU1 ctu1;

    @Override
    public void run(String... args) throws Exception {
        StateMachine ctu1_sm = ctu1.getMachine();
        log.info(ctu1_sm.getState().toString());
    }
}

方案二:保留@Async,通过ApplicationContext获取Bean

若必须异步执行run方法,可实现ApplicationContextAware接口,直接从上下文获取CTU1实例,规避注入时机问题:

@Component
@Async("myExecutor")
@Slf4j
class Commandline implements CommandLineRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) throws Exception {
        CTU1 ctu1 = applicationContext.getBean(CTU1.class);
        StateMachine ctu1_sm = ctu1.getMachine();
        log.info(ctu1_sm.getState().toString());
    }
}

额外检查项

  1. 确认异步线程池配置:确保myExecutor线程池已正确配置,若未配置,可添加如下配置类:
@Configuration
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
        executor.setThreadNamePrefix("MyExecutor-");
        executor.initialize();
        return executor;
    }
}
  1. 包扫描范围验证:确认CTU1所在的fb包在SpringBoot扫描范围内,若不在,需在@SpringBootApplication上添加@ComponentScan(basePackages = {"com.example.demo", "你的其他包路径"})指定扫描范围。
  2. 父类CTU构造函数检查:确保CTU类的构造函数是无参的,或带有@Autowired注解的有参构造函数,避免子类CTU1实例化时出现异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:22:03