简体   繁体   English

如何将原型 spring bean 注入到 singleton bean

[英]How Inject prototype spring bean to singleton bean

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:我想将我的 pojo class 更改为 spring,我在将原型 bean 注入 singelton bean 时遇到问题,我的旧代码如下:

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: Insert BankBusiness class 不是线程安全的,我需要为每个服务调用从它实例化,我现在重写了代码如下:

@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?第二种情况的行为是否与第一种情况相同?

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.在第一种情况下,每次访问时都会创建InsertBankBusiness服务,但在第二种情况下,服务会在每次 HTTP 请求时创建一次。
You need to use Prototype scope instead of Request to have the same behavior.您需要使用Prototype scope 而不是Request来获得相同的行为。

    @Scope(value= "prototype", proxyMode=TARGET_CLASS)
    public class InsertBankBusiness {

    }

InsertBankBusiness injected correctly via Scoped Proxy. InsertBankBusiness通过 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.每次调用代理 object 上的方法时,代理自己决定是创建真实 object 的新实例还是重用现有实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM