I'm using the latest Spring Boot version and trying to dynamically create n number of beans based upon what is defined in the application.yaml file. I would then like to inject these beans into other classes based upon the bean name.
The code below is a much simplified example of what I am trying to achieve. The auto configuration would normally be part of a spring boot starter library so the number of beans needed to be registered is unknown.
@Slf4j
@Value
public class BeanClass {
private final String name;
public void logName() {
log.info("Name: {}", name);
}
}
@Component
@RequiredArgsConstructor
public class ServiceClass {
private final BeanClass fooBean;
private final BeanClass barBean;
public void log() {
fooBean.logName();
barBean.logName();
}
}
@Value
@ConfigurationProperties
public class BeanProperties {
private final List<String> beans;
}
@Configuration
public class AutoConfiguration {
// Obviously not correct
@Bean
public List<BeanClass> beans(final BeanProperties beanProperties) {
return beanProperties.getBeans().stream()
.map(BeanClass::new)
.collect(Collectors.toList());
}
}
@EnableConfigurationProperties(BeanProperties.class)
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
final ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
final ServiceClass service = context.getBean(ServiceClass.class);
service.log();
}
}
beansToMake:
- fooBean
- barBean
I've tried multiple suggestions on google but nothing works and seems outdated. I'm hoping a new feature of Spring makes this straight forward.