gpt4 book ai didi

java - Spring:如何从实现通用接口(interface)的应用程序上下文中获取bean?

转载 作者:搜寻专家 更新时间:2023-10-30 23:02:07 24 4
gpt4 key购买 nike

我有接口(interface):

public interface CommandHandler<T extends Command> {
void handle(T command);
}

有实现Command标记接口(interface)的命令

public class CreateCategoryCommand implements Command {
}

public class CreateCategoryCommand implements Command {
}

对于每个命令,我都有适当的CommandHandler 实现:

@Component
public class CreateProductCommandHandler implements CommandHandler<CreateProductCommand> {
@Override
public void handle(CreateProductCommand command) {
System.out.println("Command handled");
}
}

@Component
public class CreateCategoryCommandHandler implements CommandHandler<CreateCategoryCommand> {

@Override
public void handle(CreateCategoryCommand command) {

}
}

问题:我有命令总线

@Component
public class SimpleCommandBus implements CommandBus {

@Autowired
private ApplicationContext context;

@Override
public void send(Command command) {
// OF COURSE, THIS NOT COMPILED, BUT I NEED SOMETHING LIKE THIS
CommandHandler commandHandler = context.getBean(CommandHandler<command.getClass()>)
}
}

如何从实现特定类型通用接口(interface)的应用程序上下文中获取bean?

最佳答案

我的解决方法:

@Component
public class SimpleCommandBus {

private final Logger logger;
private final Set<CommandHandler<?>> handlers;
private final Map<Class<?>, CommandHandler<?>> commandHandlersCache = new WeakHashMap<>();

public SimpleCommandBus(Logger logger, Set<CommandHandler<?>> handlers) {
this.logger = logger;
this.handlers = handlers;
}

public void send(Command command) {
CommandHandler<Command> commandHandler = getCommandHandler(command);

if (commandHandler != null)
commandHandler.handle(command);
else
logger.error("Can't handle command " + command);

}

@SuppressWarnings("unchecked")
private <C extends Command> CommandHandler<C> getCommandHandler(C command) {
Class<?> commandType = command.getClass();

if (commandHandlersCache.containsKey(commandType))
return (CommandHandler<C>) commandHandlersCache.get(commandType);

for (CommandHandler<?> haandler : handlers) {
Class<?> supportedCommandType = resolveTypeArgument(haandler.getClass(), CommandHandler.class);

if (commandType.isAssignableFrom(supportedCommandType)) {
commandHandlersCache.put(commandType, haandler);
return (CommandHandler<C>) haandler;
}
}

commandHandlersCache.put(commandType, null);
return null;
}


}

关于java - Spring:如何从实现通用接口(interface)的应用程序上下文中获取bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39881211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com