And if they are, How to stop that?
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 {
...
}
@Service
@Scope("prototype")
public class CustomerService
{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With