I have two beans, Parent and Child. Child bean I have declared as of Protoype scope.
I want new child object is used to call any child's method in the Parent class. For eg. in the below example,I want statement 1 calls method sayHi on different child object and statement 2 calls sayHi1 on different child object.
One way is to implement ApplicationContextAware and get new child object using context.getBean("")
before calling any child's method. But i don't want to do that.
Is there any other alternative?
@Component
public class Parent{
@Autowired
Child child;
public void sayHello(){
child.sayHi(); -------------- (1)
}
public void sayHello1(){
child.sayHi1(); --------------- (2)
}
}
@Component
@Scope(value=BeanDefinition.SCOPE_PROTOTYPE)
public class Child{
public void sayHi(){
System.out.println("Hi Spring 3.0");
}
public void sayHi1(){
System.out.println("Hi1 Spring 3.0 ");
}
}
The fix is simply to mark the prototype bean as a scoped proxy, what this means is that a when you inject a bean of a smaller scope into a larger scope(like in your case where a prototype is injected into a singleton) then a proxy of the bean will be injected into the larger scope and when methods of the bean are invoked via proxy, the proxy understands the scope and will respond appropriately.
@Component
@Scope(value=BeanDefinition.SCOPE_PROTOTYPE, proxyMode=ScopedProxyMode.TARGET_CLASS)
public class Child{
Here is a reference
Another option could be to use something called lookup method injection described here
I think you have to make a new Child
yourself each time or indeed use the spring context to get a fresh bean.
Spring will only create a new instance when it needs to inject something (in case of prototype). When you are in a class you are effectively out of the scope of spring.
Here is a similar post: @Scope("prototype") bean scope not creating new bean
http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-prototype Parts 4.4.2 and 4.4.3 are relevant.
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