Spring FactoryBean and scopes working together

前端 未结 2 807
面向向阳花
面向向阳花 2021-02-08 23:56

I\'d like to use FactoryBeans and scopes together. Specifically, I\'d like the object created and returned by a FactoryBean to be placed into a specified (perhaps custom) scope.

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 00:48

    You can't easily use a custom scope on a bean returned from a FactoryBean.

    From Spring's Java documentation:

    FactoryBeans can support singletons and prototypes

    If you want the FactoryBean's returned bean to have the prototype scope, then you must implement the isSingleton() method like this:

    public class TestFactoryBean implements FactoryBean {
    
      // the rest of the required methods are removed for simplicity reasons..
    
      public boolean isSingleton() {
            return false;
        }
    }
    

    To support a custom scope, you have to implement the logic yourself and it will not be very intuitive, since the FactoryBean only provides the isSingleton() method. I will rather recommend using another solution than FactoryBean for beans with custom scope.

    Hope this helps!

提交回复
热议问题