Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are @Autowired or @Resource fields singletons?

Tags:

java

spring

I'm maintaining an old application but am unfamiliar with Spring Framework. I'm working on a class that currently looks like this:

public class Foo {

    @Resource(name = "fb")
    private FooBar fb;

    @Resource
    private FooBar2 fb2;

    @Autowired
    private FooBar3 fb3 = null;

    ...
}

and an XML file that looks like this:

<beans xmlns="http://www.springframework.org/schema/beans" ... >
    <context:annotation-config/>
    ...
    <bean id="fb3" class="FooBar3"/>
    ...
</beans>

In some other method, the class Foo is instantiated:

void carryOutSomeFoobarring() {
    Foo f = new Foo();
    ...(use f)...
}

If carryOutSomeFoobarring is called at the same time from two different threads, there will, of course be two separate Foo instances of the local variable f. But will both instances of field f.fb refer to the same injected FooBar object? What about f.fb2 and f.fb3?

like image 726
DodgyCodeException Avatar asked Sep 05 '25 01:09

DodgyCodeException


1 Answers

By default they're singletons. If the scope is changed to prototype, you get separate objects.

like image 168
Kayaman Avatar answered Sep 07 '25 15:09

Kayaman