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

旧Spring 1.2.6调用Spring Boot 5.0.7时Autowired注入Bean为空问题

问题根因

你当前用Spring 1.2.6的容器实例化TestPci对象,Spring 1.2.6版本发布时不存在@Autowired、@Service等注解,完全无法识别Spring 5的注解能力,也不会处理TestWebClientService的注入逻辑,因此注入字段必然为空。JUnit测试能正常运行是因为测试用Spring 5的容器启动,所有注解都能被正确解析。

可行解决方案

方案1:同进程部署时从Spring Boot上下文获取实例(推荐)

该方案直接从Spring 5的容器中获取已经完成全部注入逻辑的TestPci实例,规避旧版本Spring的注解兼容问题:

  1. 先在Spring Boot启动类中暴露上下文的静态获取入口:
@SpringBootApplication
public class YourBootApplication {
    private static ApplicationContext bootContext;
    public static void main(String[] args) {
        bootContext = SpringApplication.run(YourBootApplication.class, args);
    }
    // 对外提供获取Spring Boot容器中Bean的静态方法
    public static <T> T getBootBean(Class<T> beanClazz) {
        return bootContext.getBean(beanClazz);
    }
}
  1. 删掉旧Spring项目XML中TestPci的Bean配置,修改A类的Bean获取逻辑:
public TestPci getTestService() {
    if (!StringUtils.isValid(this.testPci)) {
        // 直接从Spring Boot上下文拿已完成注入的实例
        testPci = YourBootApplication.getBootBean(TestPci.class);
        this.setSecureTestService(testPci);
    }
    return this.testPci;
}
  1. 依赖冲突处理:用Maven Shade插件把Spring Boot相关依赖做重命名隔离,避免和旧版本Spring的类冲突。

方案2:封装为独立接口服务(最稳妥,无依赖冲突)

把TestPci的业务能力封装为HTTP接口或者RPC接口,旧Spring项目直接调用接口即可,不需要处理任何Spring版本兼容问题,适合跨应用部署的场景。

方案3:手动完成依赖注入(不推荐,维护成本高)

如果必须保留旧Spring中TestPci的实例化逻辑,可以在TestPci中手动获取依赖,不需要依赖@Autowired注入:

@Service
@Configurable
public class TestPci{
    private TestWebClientService testWebClientService;

    public TestPci() {
        // 构造时主动从Spring Boot上下文获取依赖
        this.testWebClientService = YourBootApplication.getBootBean(TestWebClientService.class);
    }

    public Map<String, String> testing(String a, String b, String c) throws Exception {
        Map<String, String> map =  testWebClientService.find(a, b, c);
        System.out.println("**=="+map.get(0));
        return map;
    }
}

该方案要求Spring Boot应用必须在TestPci实例化之前完成启动,否则会抛出空指针异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:39:01