AhHatem
AhHatem

Reputation: 1435

Are Spring's @Autowired object reused?

And if they are, How to stop that?

Upvotes: 4

Views: 3926

Answers (2)

NimChimpsky
NimChimpsky

Reputation: 47290

@Service
@Scope("prototype")
public class CustomerService 
{}

Upvotes: 3

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

It depends on the scope of the bean being annotated. If it is of scope singleton, then it the same instance will be used everywhere in the Spring ApplicationContext. If it is of scope prototype, then a new instance will be used in each location.

<bean id="id" class="some.NewObject" scope="prototype"/>
<bean id="id2" class="some.AnotherNewObject" scope="singleton"/>

These bean definitions coupled with the following code will help to illustrate.

class Class1 {
    @Autowired
    some.AnotherNewObject obj;
}

class Class2 {
    @Autowired
    some.AnotherNewObject obj;
}

class Class3 {
    @Autowired
    some.NewObject obj;
}

class Class4 {
    @Autowired
    some.NewObject obj;
}

Class1 and Class2 will receive a reference to the same instance of some.AnotherNewObject. Class3 and Class4 will receive references to different instances of some.NewObject.

If you are using annotations and package scanning for configuration, then you can can use the @Scope annotation to specify your scope:

@Component
@Scope("prototype")
class NewObject {
    ...
}

@Component
@Scope("singleton")
class AnotherNewObject {
    ...
}

Upvotes: 9

Related Questions