java - 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...
}
解决方案
使用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 泛型基础
推荐阅读
- python-3.x - Python Concatenante Integer 和 String 然后将变量设为整数格式
- php - 如果视频不存在,则仅从数据库中输出无效的 YouTube ID
- docker - 如何使用私有 docker 注册表而不是 docker hub?
- python - 如何在抓取锚点时处理错误
- java - 尽管包含正文,邮递员 POST 请求仍发送空流
- python - 如何将 .h5 文件(Keras)上传到 Azure Blob 存储而不用 Python 将其保存在磁盘中
- c# - Json 值字段内的 Json 字符串
- opc - OPC UA 中的用户令牌类型
- amazon-web-services - AWS lambda 超时和 getRemainingTimeInMillis()
- python - 如何在熊猫中有效地循环两次相同的数据帧并在达到条件时中断?