I want to create a Spring bean in Spring Java configuration with some constructor arguments passed at runtime. I have created the following Java config, in which there is a bean fixedLengthReport that expects some arguments in constructor.
@Configuration
public class AppConfig {
@Autowrire
Dao dao;
@Bean
@Scope(value = "prototype")
**//SourceSystem can change at runtime**
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
}
But i am getting error that sourceSystem couldn't wire because no bean found. How can I create bean with runtime constructor arguments?
I am using Spring 4.2
This can be achieved with Spring's
ObjectProvider<>
class which was introduced in Spring 4.3. See Spring's documentation for additional details.The gist is to define the bean factory method for the object to be provided, inject the
ObjectProvider<>
in your consumer and create new instances of the object to be provided.NOTE: you don't actually implement the
ObjectProvider<>
interface; Spring does that for you automagically. You just need to define the bean factory method.You can use a prototype bean along with a
BeanFactory
.@Scope(value = "prototype")
means that Spring will not instantiate the bean right on start, but will do it later on demand. Now, to customize an instance of the prototype bean, you have to do the following.Note, because your bean cannot be instantiated on start, you must not Autowire your bean directly; otherwise Spring will try to instantiate the bean itself. This usage will cause an error.
You code looks fine, to get the prototype with parameters use the BeanFactory#getBean(String name, Object... args) method.
Look at Spring Java Config: how do you create a prototype-scoped @Bean with runtime arguments? BeanFactory#getBean(String name, Object... args) would be what you are looking for.
I guess that your IDEA (in my case IntelliJ IDEA version 15.) give you the error and it’s not a runtime/compile time error.
In IntelliJ you can change the setting of Spring inspections.