I have interface:
public interface CommandHandler<T extends Command> {
void handle(T command);
}
There are commands which implement Command marker interface
public class CreateCategoryCommand implements Command {
}
public class CreateCategoryCommand implements Command {
}
For each command I have apropriate CommandHandler implementations:
@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) {
}
}
Question: I have command bus
@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()>)
}
}
How to get bean from application context which implements generic interface with particular type?
Way I solved it: