Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Spring's @Autowired object reused?

And if they are, How to stop that?

like image 204
AhHatem Avatar asked Nov 01 '25 02:11

AhHatem


2 Answers

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 {
    ...
}
like image 68
nicholas.hauschild Avatar answered Nov 04 '25 01:11

nicholas.hauschild


@Service
@Scope("prototype")
public class CustomerService 
{}
like image 38
NimChimpsky Avatar answered Nov 04 '25 00:11

NimChimpsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!