简体   繁体   中英

Spring instantiate prototype beans by manual call

I have a @Configuration class that I try to use for the sake of custom configuration of JMS components of my application. Here it's simplified code:

@Configuration
class JmsConfiguration(
    val props: JmsProperties
) : JmsListenerConfigurer {
    @Bean
    fun connectionFactoryManager(): ConnectionFactoryManager {
        return ConnectionFactoryManager(props.services.map { serviceProps ->
            connectionFactory(serviceProps)
        }.toList())
    }

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    fun connectionFactory(serviceProps: JmsServiceProps): ConnectionFactory {
        val cf = MQConnectionFactory()
        // some configuration
        return cf
    }

    override fun configureJmsListeners(registrar: JmsListenerEnpointRegistrar) {
        // adding custom message listeners to registrar
    } 
}

The thing is that Spring complains about connectionFactory method and it's parameter serviceProps saying the following: "Parameter 0 of method connectionFactory in JmsConfiguration required a bean of type JmsServiceProps that could not be found" which is pretty strange. I thought that spring doen't lookup parameters for prototype scoped bean factory methods? If this is not the case and I'm wrond how should I create such instances?

Note: I need these connection factories to be present in spring context since they are being wrapped by other components thereafter.

Unless that properties file is a @Bean , you need tell Spring about it. The simplest way is to do:

@Configuration 
@EnableConfigurationProperties(JmsServiceProps.class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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