0

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 ?

sagar kancherla
  • 129
  • 1
  • 3
  • 12

1 Answers1

0

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

Ali Dahaghin
  • 77
  • 1
  • 11
  • How can I dynamically initialise mybean2 ? Depending on the property mybean.names – sagar kancherla Jun 18 '20 at 03:30
  • it is not a common approche to initialize bean dynamically. so if you have to, you can add it to applicationContext manually after spring boot started. see [link](https://stackoverflow.com/questions/4540713/add-bean-programmatically-to-spring-web-app-context) and [link](https://stackoverflow.com/questions/27405713/running-code-after-spring-boot-starts). but still the best way is adding new @Bean method as i said in answer – Ali Dahaghin Jun 19 '20 at 09:40