首页 > 解决方案 > java - 如何在java Spring Boot中实现一个通用服务类?

问题描述

我有许多具有重复代码的服务,我想知道如何实现通用服务,以便我的所有服务都可以扩展它。

服务接口示例(重复代码):

@Service
public interface IUserService{    
    List<User> findAll();
    User save(User entity);
    User findById(long id);
    void delete(User entity);
    void deleteById(long id);
    long count();
}

@Service
public interface IEventService{ 

    List<Event> findAll();
    Event save(Event entity);
    Event findById(long id);
    void delete(Event entity);
    void deleteById(long id);
    long count();
}

以及它们的实现(现在,我在所有实现中都有相同的代码):

@Service
public class EventService implements IEventService{

    @Autowired
    private IEventDao dao;

    @Override
    public List<Event> findAll() {
        return dao.findAll();
    }

    @Override
    public Event save(Event entity) {
        return dao.save(entity);
    }

   Other CRUD methods...

}

@Service
    public class UserService implements IUserService{

        @Autowired
        private IUserDao dao;

        @Override
        public List<User> findAll() {
            return dao.findAll();
        }

        @Override
        public User save(User entity) {
            return dao.save(entity);
        }

       Other CRUD methods...

    }

标签: javaspringspring-bootspring-data-jpaspring-data

解决方案


使用Java 泛型是相当简单的。您可以用类型参数替换实际的 class User,Event等。

public interface IGenericService<T> {    
    List<T> findAll();
    T save(T entity);
    T findById(long id);
    void delete(T entity);
    void deleteById(long id);
    long count();
}

然后对实现做同样的事情:

public class GenericService<T> implements IGenericService<T> {

    // The DAO class will also need to be generic,
    // so that it can use the right class types
    @Autowired
    private IDao<T> dao;

    @Override
    public List<T> findAll() {
        return dao.findAll();
    }

    @Override
    public T save(T entity) {
        return dao.save(entity);
    }

    // Other CRUD methods...

}

更进一步,您还可以将您的实际服务创建为:

@Service
class UserService extends GenericService<User> { }

@Service
class EventService extends GenericService<Event> { }

这是 Java 文档中的一个很好的教程:学习 Java 语言:泛型

另一个有很好例子的:Java 泛型基础


推荐阅读