How to create beans dynamically in spring custom starter based on property

293 Views Asked by At

I am writing a custom spring starter, in which I need to register a list of beans of same type based on the property defined in the application.properties

i have following properties in application.properties

mybean.names = mybean1, mybean2
mybean1.foo = foo1
mybean2.foo = foo2
mybean1.bar = bar1
mybean2.bar = bar2

Current implementation of autoconfiguration class is below

@Configuration
@ConditionalOnClass(MyBeanFactory.class)
public class MyBeanAutoConfiguration {
@Autowire
Environemnt evn;

@Bean(name = {"mybean1"})
public MyBean getBean() {
  String[] names = StringUtils.commaDelimitedListToStringArray(evn.getProperty("mybean.names"));
  MyBean mybean = new Mybean(evn.getProperty(names[0] + ".foo"), 
                               evn.getProperty(names[0] + ".bar"));
return myBean;

}

}

And i want to simply autowire with qualifer my bean in spring boot application like below

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

  @Autowired
  @Qualifer("mybean1")
  MyBean mybean;

  public static void main(String[] args) {
    SpringApplication.run(VaultApplication.class, args);
  }

How can i change my autoconfigure class to create multiple beans with different names defined in the properties file(in this case how can I create bean mybean2) so that i can use simply autowire with qualifier ?

1

There are 1 best solutions below

2
On

I am not sure that i understood you question but if you want to have several bean with different name so best way is writing multiple @Bean method in your configuration class with different name, so you can autowire each one of them by @Qualifer