Spring FactoryBean and scopes working together

前端 未结 2 813
面向向阳花
面向向阳花 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:57

    I solved the same issue using custom holder bean.

    Factory bean:

    @Component
    @Configurable()
    public class EventBusFactory implements FactoryBean {
        @Override
        public EventBus getObject() throws Exception {
            return new SimpleEventBus();
        }
    
        @Override
        public Class getObjectType() {
            return EventBus.class;
        }
    
        @Override
        public boolean isSingleton() {
            return false;
        }
    }
    

    Bean holder:

    @Configurable
    @Component
    @Scope("session")
    public class EventBusHolder {
    
        @Autowired
        private EventBus eventBus;
    
        public EventBus getEventBus() {
            return eventBus;
        }
    
        public void setEventBus(EventBus eventBus) {
            this.eventBus = eventBus;
        }
    }
    

    And then I use holder instead of the required entity.

    @Component
    @Configurable
    @Scope("session")
    public class UicPlaceController extends PlaceController {
    
        @Autowired
        public UicPlaceController(EventBusHolder eventBus) {
            super(eventBus.getEventBus());
        }
        ...
     }
    

    The solution looks a little bit ugly, but still, it solves the issue.

提交回复
热议问题