@Inject在基于子类的抽象类中

时间:2014-03-19 13:15:42

标签: java polymorphism

让我想象一下,每个实体都有一个用于数据库访问和服务类的存储库类(spring data jpa)。依赖关系由spring框架管理。在大多数情况下,每种服务方法都是相同的,因此主要是代码重复:

public class NewsService {
    @Inject
    private NewsRepository newsRepository;

    public void add(News news) {
        // do some validation
        newsRepository.save(news);
    }
}

public class UserService {
    @Inject
    private UserRepository userRepository;

    public void add(User user) {
        // do some validation
        userRepository.save(user);
    }
}

现在我考虑创建一个这样的抽象类:

public abstract class AbstractService<T> {
    private UnknownRepository unknownRepository;

    public void add(T entity) {
        // do some validation
        unknownRepository.save(entity);
    }
}

public class NewsService extends AbstractService<News> {

}

public class UserService extends AbstractService<User> {

}

我的问题:如何根据我的实体覆盖抽象类中使用的存储库?

1 个答案:

答案 0 :(得分:2)

您可以使用抽象方法和类型参数替换UnknownRepository字段:

// R is the type of the repository
public abstract class AbstractService<T,R extends BaseRepository> {
    protected abstract R getRepository();

    public void add(T entity) {
        getRepository().save(entity);
    }
}

将特定存储库注入此类的实现:

public class NewsService extends AbstractService<News, NewsRepository> {
    @Inject private NewsRepository newsRepository;

    @Override
    public NewsRepository getRepository() {
        return newsRepository;
    }

    // the inherited add() method works now
}