简体   繁体   English

如何动态创建多个相同类型的bean然后收集/自动装配它们

[英]how to dynamically create multiple beans of same type then gather/autowire them

let's say that in my spring(boot) yaml config file I have a list of commands:假设在我的 spring(boot) yaml 配置文件中,我有一个命令列表:

commands: [add,delete,copy,move] 

and the corresponding class in my spring(boot) project:以及我的 spring(boot) 项目中相应的 class :

public class Command {

    private String name;

    public Command(String name) {
        this.name = name;
    }

    public void execute() {
        System.out.println(name);
    }

    public String getName() {
        return name;
    }

}

How can I dynamically/adaptively generate the right number of command beans, then gather/autowire them in a separate class as below?如何动态/自适应地生成正确数量的命令 bean,然后在单独的 class 中收集/自动装配它们,如下所示?

public class Menu {

   @Autowired
   List<Command> commands;

   public void display() {
       commands.forEach(cmd -> System.out.println(cmd.getName());
   }

}

Thank you very much in advance for your time and your expertise.非常感谢您的时间和专业知识。

Regards问候

For dynamic bean registration, you can use ImportBeanDefinitionRegistrar .对于动态 bean 注册,您可以使用ImportBeanDefinitionRegistrar

The code will be like this:代码将是这样的:

import java.util.List;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

@Configuration
@Import(CommandsConfiguration.Registrar.class)
public class CommandsConfiguration {

    static class Registrar implements ImportBeanDefinitionRegistrar {

        @Override
        public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
            final List<String> commands = // read commands from environemnt/config
            for (String command : commands) {
                final String beanName = command + "Command";
                final BeanDefinition beanDefinition = BeanDefinitionBuilder
                    .genericBeanDefinition(Command.class, () -> new Command(command))
                    .getBeanDefinition();
                registry.registerBeanDefinition(beanName, beanDefinition);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM