I want to change my pojo class to spring, I have a problem for injection protoype bean to singelton bean, My old code was as follows:
public class InsertBankBusiness(){
private ServiceInput input;
public void doBusiness(ServiceInput input){
this.input = input;
....
}
},
public class BankService(){
public void definebank(ServiceInput input){
InsertBankBusiness insertBankBusiness = InsertBankBusiness ()
insertBankBusiness .doBusiness(input)
}
}
Insert BankBusiness class is not thread safe and I need to instantiate from it for every service call, I have now rewritten the code as follows:
@Component(value="insertBankBusiness")
@Scope(value="request", proxyMode=TARGET_CLASS)
public class InsertBankBusiness(){
private ServiceInput input;
public void doBusiness(ServiceInput input){
this.input = input;
....
}
},
@Service(value="bankService")
public class BankService(){
@Autowire InsertBankBusiness insertBankBusiness;
public void definebank(ServiceInput input){
insertBankBusiness.doBusiness(input)
}
}
Is the behavior of the second scenario the same as the first scenario?
CodePudding user response:
Not the same.
In the first scenario, you create InsertBankBusiness
service each time when access it, but in the second scenario, service creates once per HTTP request.
You need to use Prototype
scope instead of Request
to have the same behavior.
@Scope(value= "prototype", proxyMode=TARGET_CLASS)
public class InsertBankBusiness {
}
InsertBankBusiness
injected correctly via Scoped Proxy. Each time the method on the proxy object is called, the proxy decides itself whether to create a new instance of the real object or reuse the existing one.