简体   繁体   English

将 Spring Beans 映射到 Integer 标识符

[英]Mapping Spring Beans To Integer Identifiers

My application uses a set of command classes with unique integer identifiers to execute different tasks.我的应用程序使用一组具有唯一标识符 integer 的命令类来执行不同的任务。 Commands are stored in an enum class of form命令存储在 class 形式的枚举

public enum CommandType {

    COMMAND1(1000, Command1.class),
    COMMAND2(1001, Command2.class),
    ...

In the legacy code, we were constructing the corresponding command instance using the command id when a request is received.在遗留代码中,我们在收到请求时使用命令 ID 构造相应的命令实例。 Recently I added Spring support and now each command is marked with @Controller annotation.最近我添加了 Spring 支持,现在每个命令都标有@Controller注释。 Instead of constructing a new instance, now we do现在我们不是构建一个新实例,而是

Class<? extends Command> commandClass = commandType.getCommandClass();    
applicationContext.getBean(commandClass);

Command ids are stored in a hashmap and we obtain the corresponding commands from this map命令id存储在一个hashmap中,我们从这个map中获取相应的命令

private Map<Integer, CommandType> commandTypeMap = new HashMap<>();

What I wonder is instead of using a hashmap, can I utilize Spring. Is there an easy and graceful way to map the command beans into unique command ids in the Spring Framework, so that I can acquire the command by passing the id into Spring?我想知道的是,我可以使用 Spring 而不是使用 hashmap 吗?有没有一种简单而优雅的方法可以将命令 bean map 转换为 Spring 框架中的唯一命令 id,以便我可以通过将 id 传递到 Spring 来获取命令?

@Controller annotation can have as parameter the bean name @Controller注释可以将 bean 名称作为参数

Example:例子:

@Controller("1000") 
public class COMMAND1{
}

and then you can get instance of this bean by using his name然后你可以通过使用他的名字来获取这个bean的实例

Command1 cmd1=(Command1) applicationContext.getBean("1000");

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

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