Search code examples
springdependency-injectionautowired

Why autowired as field singletone component is not the same as autowired in method


I faced with a strange issue. I have a simple component(singletone)

@Component
public class SingletonExample {
    private String value;

    public String getValue() {
        return value;
    }

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

And 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);
    }
}

Result

example hashcode = 1063350459 Value = ABC (okay)

example2 hashcode = 1063350459 Value = ABC (okay)

example3 hashcode = 750544796 Value = null (???)

I was expected that example, example2 and example3 must be the same object. But in fact I see that only example and example2 (injected as Field) are the same, but example3(injected in method) has another hashcode and value. After line example.setValue("ABC") example3 still has value=null and hashcode is not the same as exaple and example2. Why the example3 is an another object?


Solution

  • As described in the Autowired java doc

    Autowired Parameters

    Although @Autowired can technically be declared on individual method or constructor parameters since Spring Framework 5.0, most parts of the framework ignore such declarations. The only part of the core Spring Framework that actively supports autowired parameters is the JUnit Jupiter support in the spring-test module (see the TestContext framework reference documentation for details).