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

为何字段注入的Singleton组件与方法参数注入的实例不同?

单例组件在方法参数中注入出现不同实例的问题分析

问题描述

定义了SingletonExample单例组件,在RestController中,通过字段@Autowired注入的example和example2是同一个实例,但在请求方法参数中@Autowired注入的example3却是另一个实例。调用example.setValue("ABC")后,example3的value仍为null,哈希值也与前两者不同。

相关代码

SingletonExample 类

@Component
public class SingletonExample {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

RestController 类

@RestController
public class RestController {
    @Autowired
    SingletonExample example;

    @Autowired
    SingletonExample example2;

    @GetMapping("/get_single")
    public String getHash2(@Autowired SingletonExample example3) {
        example.setValue("ABC");
        String value1 = String.format("example hashcode = %s Value = %s", example.hashCode(), example.getValue());
        String value2 = String.format("example2 hashcode = %s Value = %s", example2.hashCode(), example2.getValue());
        String value3 = String.format("example3 hashcode = %s Value = %s", example3.hashCode(), example3.getValue());
        return value1.concat("<br>").concat(value2).concat("<br>").concat(value3);
    }
}

请求返回结果

example hashcode = 1063350459 Value = ABC (okay)
example2 hashcode = 1063350459 Value = ABC (okay)
example3 hashcode = 750544796 Value = null (?)

问题原因与解决方案

原因分析

  • Spring中,方法参数上的@Autowired注解并非用来注入容器内的单例Bean,它实际触发了@ModelAttribute的逻辑:Spring会为当前请求创建一个SingletonExample的新实例,尝试通过请求参数绑定其属性(即使没有请求参数,也会实例化新对象),这个实例不属于Spring容器管理的单例池,因此和字段注入的实例不是同一个对象。
  • 字段注入的example和example2是Spring容器初始化时创建的单例实例,因此指向同一个对象,修改其属性后两者都会同步变化。

解决方案

  1. 直接移除方法参数上的@Autowired注解,方法内直接使用类中已注入的example或example2即可获取单例实例。
  2. 如果确实需要在方法参数中获取容器内的单例Bean,可改用@RequestAttribute将Bean存入请求属性后再获取,但这种场景不推荐,直接使用字段注入是更规范的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:22:21