嘗試在Micronaut中做java泛型類的依賴注入
界面
public interface IRequestHandler<C, R> {
R handler(C c);
}
依賴注入
@Singleton
public record ServiceBus(IRequestHandler<C, R> iRequestHandler) implements IServiceBus{
@Override
public <C, R> R send(C c) {
return iRequestHandler.handler(c);
}
}
界面
public interface IServiceBus {
<C,R> R send(C c);
}
執行
public class ProductController {
public ProductController(IServiceBus iRequestHandler){
_iserviceBus= iRequestHandler;
}
public Mono<?> get(ProductSearchCriteriaCommand searchCriteria) {
var item = _iserviceBus.<CreateProductCommand,CreateProductCommand>send(new CreateProductCommand());
return null;
}
}
我的問題是在 ServiceBus 類上,我如何為public record ServiceBus(IRequestHandler<C, R> iRequestHandler)
和傳遞型別iRequestHandler.handler(c);
@Singleton
public class CreateProductCommandHandler implements IRequestHandler<CreateProductCommand, CreateProductCommand> {
@Override
public CreateProductCommand handler(CreateProductCommand createProductCommand) {
return null;
}
}
@Singleton
public record DeleteProductCommandHandler() implements IRequestHandler<DeleteProductCommand,DeleteProductCommand> {
@Override
public DeleteProductCommand handler(DeleteProductCommand deleteProductCommand) {
return null;
}
}
當我_iserviceBus.<CreateProductCommand,CreateProductCommand>send(new CreateProductCommand());
在控制器中呼叫時,我試圖handler
在CreateProductCommandHandler
類中呼叫方法
同樣,如果我呼叫類_iserviceBus.<CreateProductCommand,CreateProductCommand>send(new DeleteProductCommand());
的handler
方法DeleteProductCommandHandler
應該得到呼叫
uj5u.com熱心網友回復:
您錯誤地定義了 IServiceBus 介面:
public interface IServiceBus {
<C,R> R send(C c);
}
應該:
public interface IServiceBus<C,R> {
R send(C c);
}
更新。非常基本的注冊表示例。
public interface IRequestHandler<C, R> {
R handler(C c);
Class<C> getCmdType();
}
public class ServiceBus implements IServiceBus {
private final Map<Class<?>, IRequestHandler<?, ?>> handlerMap;
public ServiceBus(List<IRequestHandler<?, ?>> handlers) {
handlerMap = handlers.stream()
.collect(toMap(
IRequestHandler::getCmdType,
Function.identity()
));
}
@Override
public <C, R> R send(C c) {
IRequestHandler<C, R> handler = (IRequestHandler<C, R>) handlerMap.get(c.getClass());
if (handler == null) {
throw new UnsupportedOperationException("Unsupported command: " c.getClass());
}
return handler.handler(c);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376626.html
上一篇:如何在laravel8中的storage/app/public/student_img檔案夾中在我的視圖刀片中顯示影像