java—如何将泛型类类型传递给@component?

mm9b1k5b  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(190)

我想在spring应用程序中为服务层编写exceptionhandler。
我希望它是泛型的(获取类类型并基于它返回相应的消息)。所以应该是这样的:

@Service
BookService

private final ExceptionHelper<Book> exceptionHelper;

@Transactional
public Book getBook(Long id) {
    return bookRepository.findById(id).orElseThrow(
            exceptionHelper.getEntityNotFoundException(id));
}

在exceptionhelper中,它应该基于它获取类型和返回值:

@Component
public class ExceptionHelper<T> {

    private Class<T> type;

    public ExceptionHelper() {

    }

    public ExceptionHelper(Class<T> type) {
        this.type = type;
    }

    Supplier<EntityNotFoundException> getEntityNotFoundException(Long id) {
        return () -> new EntityNotFoundException(format("Cannot find %s with given id: %d", type.getSimpleName(), id));
    }
}

所以它应该返回“找不到具有给定id:5的书”,但抛出nullpointerexception,因为类型为空。如何将其(类型)传递给exceptionhelper?
我当前的解决方案是显式地将book.class传递给方法。

private final ExceptionHelper<Book> exceptionHelper;

return bookRepository.findById(id).orElseThrow(
                exceptionHelper.getEntityNotFoundException(id, Book.class));

在exceptionhelper中:

Supplier<EntityNotFoundException> getEntityNotFoundException(Long id, Class<T> entityType) {
        return () -> new EntityNotFoundException(format("Cannot find %s with given id: %d", entityType.getSimpleName(), id));
    }

但是我有没有每次都做(通过书,课),哪怕是一节课5次?有更好的办法吗?也许我甚至不应该使用@component和use = new 我自己初始化?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题