如何在singleton bean中制作原型bean?

时间:2017-11-21 11:11:16

标签: java spring dependency-injection factory

我需要能够创建新的bean实例 - 不是每次调用proxyMode=*中的方法,而是仅在需要时(例如调用.getObject())。

我知道有ObjectFactoryServiceFactory,但问题是我无法在java配置中定义工厂,但必须在bean中使用硬编码字符串。所以这就是我想要实现的目标:

@Configuration
    class Config {
        @Bean
        public MessageListenerContainerFactory listenerContainerFactory() {
            MessageListenerContainerFactory listenerContainerFactory = new MessageListenerContainerFactory();
            listenerContainerFactory.setMessageListener(rabbitProcessor());
            return listenerContainerFactory;
        }

        @Bean
        @Scope(SCOPE_PROTOTYPE)
        public MessageListener rabbitProcessor() {
            return new RabbitProcessor();
        }

        @Bean
        @Scope(SCOPE_PROTOTYPE)
        public MessageListener notThisOne() {
            return new NotThisOne();
        }
    }

    class MessageListenerContainerFactory {

        private MessageListener messageListener;

        public void setMessageListener(MessageListener messageListener) {
            this.messageListener = messageListener;
        }

        public SimpleMessageListenerContainer createListenerContainer(){
            SimpleMessageListenerContainer setMessageListener= new SimpleMessageListenerContainer();

            //THIS HERE IS NEEDED!!!
            Object needed = SPRINGCONTEXT.GETBEANNAMEOF(this.messageListener).getObject();


            listenerContainer.setMessageListener(needed);
            return setMessageListener;
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试@Qualifier注释。

参考 - http://zetcode.com/articles/springbootqualifier/

@Bean
        @Qualifier("rabbitProcessor")
        @Scope(SCOPE_PROTOTYPE)
        public MessageListener rabbitProcessor() {
            return new RabbitProcessor();
        }

        @Bean
        @Qualifier("notThisOne")
        @Scope(SCOPE_PROTOTYPE)
        public MessageListener notThisOne() {
            return new NotThisOne();
        }

然后,只要你需要,就可以通过在applicationContext上调用getBean()来创建对象。

applicationContext.getBean("rabbitProcessor");
//or
applicationContext.getBean("notThisOne");