Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

java - Spring prototype beans in combination with singleton beans and dependency injection. Is there an approach that is configuration only?

I have a singleton bean which needs for each call of a function to return a reference to a different (new) prototype bean. The only way that I can think of doing this is to programmatically retrieve a new prototype bean instance from the BeanFactory/ApplicatioContext by invoking its getBean() method. Code sample will follow...

Is there a better way to do this? Only via configuration, hopefully? (Personally, I doubt there is...)

<bean id="protoBean" scope="prototype"
        class="com.blahblah.ProtoBean" />

<bean id="singletonBean"
        class="com.blahblah.SingletonBean" />

public class ProtoBean {

    ....
}

public class SingletonBean {

    private BeanFactory factory;

    public ProtoBean dispense() {
        return (ProtoBean) factory.getBean("protoBean");
    }

    ....
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

take a look at Method Injection


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...