@Inject in abstract class based on subclass

不羁岁月 提交于 2019-12-25 02:34:32

问题


let imagine I have per entity a repository class (spring data jpa) for database access and a service class. The dependencies are managed by spring framework. Every service method does in most cases the same, so there is mainly code duplication:

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);
    }
}

Now i thought about creating an abstract class like this:

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> {

}

My problem: How can i overwrite the repository used inside the abstract class based on my entities?


回答1:


You can replace the UnknownRepository field with an abstract method and a type parameter:

// 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);
    }
}

And inject the specific repository to the implementations of this class:

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

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

    // the inherited add() method works now
}


来源:https://stackoverflow.com/questions/22507041/inject-in-abstract-class-based-on-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!