Reputation: 67
I have a bean declared in by config file as:
@Bean
@Lazy
@Scope("prototype")
public SomeClass someClass()
{
return new SomeClass();
}
Then inside my test class I have the following code:
@Autowired
private SomeClass someClass;
@Before
public void setUp()
{
xyzObject.someMethod(someClass);
}
My question here is inside my setUp()
method I am just referencing the autowired SomeClass
bean but not getting it from the spring context using getBean()
, but still it is creating a new bean everytime the setUp()
is running before a test. Why is this happening? Does prototype scope means a new bean gets created whenever the bean's reference is used anywhere in the code? I haven't seen anything specified like that in the documentation.
Upvotes: 1
Views: 286
Reputation: 7798
That is the essence of Inversion of Control. Because you injected it into another bean, every time you instantiate another bean your injected bean would be created and provided by spring as part of instantiation of your containing bean. You don't need to call getBean()
here. However if in some place you just need an instance of your SomeClass
bean you may call getBean()
to tell your spring environment to give you that bean to you. However, It is better to avoid such practice and rely on injection. Or create a Factory that can provide you such Bean (Still relaying on spring though) That would make your code not aware of Spring which is IMHO is more ellegant
Upvotes: 1