Anyone using Spring or Spring Boot, knows about Beans & we use @Autowired a lot to create the beans via Spring.
Points to note-
a) To create the bean, Spring needs 'no argument' constructor to create the instance.
b) If 'no argument' constructor is not present then one will get the error if used @Autowired for
such class.
c) But what if we need to use parametrized constructor then we can create the custom
Configuration class to enable Spring to create the beans. In such class we can provide the
@Bean annotated methods to provide the beans.
d) @Autowired causes the bean to created during application start, but @Bean works as Lazy initialization.
But issue comes when one needs to provide the constructor parameters at runtime to create the beans via Spring. As using @Bean, one can use parameterized constructor but those can be given during compile time only.
So the interesting solution is given here -
java - Spring bean with runtime constructor arguments - Stack Overflow
Here usage of BeanFactory is suggested to get the beans while passing the constructor arguments.
public class ConditionalBean {
public ConditionalBean(String msg) {
System.out.println("ConditionalBean created with msg " + msg);
}
}
Then in the class where we need its bean, we can use-
String msg = "parameter";
ConditionalBean cb = (ConditionalBean)beanFactory.getBean(ConditionalBean.class, msg);
Points to note-
a) To create the bean, Spring needs 'no argument' constructor to create the instance.
b) If 'no argument' constructor is not present then one will get the error if used @Autowired for
such class.
c) But what if we need to use parametrized constructor then we can create the custom
Configuration class to enable Spring to create the beans. In such class we can provide the
@Bean annotated methods to provide the beans.
d) @Autowired causes the bean to created during application start, but @Bean works as Lazy initialization.
But issue comes when one needs to provide the constructor parameters at runtime to create the beans via Spring. As using @Bean, one can use parameterized constructor but those can be given during compile time only.
So the interesting solution is given here -
java - Spring bean with runtime constructor arguments - Stack Overflow
Here usage of BeanFactory is suggested to get the beans while passing the constructor arguments.
public class ConditionalBean {
public ConditionalBean(String msg) {
System.out.println("ConditionalBean created with msg " + msg);
}
}
Then in the class where we need its bean, we can use-
String msg = "parameter";
ConditionalBean cb = (ConditionalBean)beanFactory.getBean(ConditionalBean.class, msg);