How to implement a generic service class in java Spring Boot?
14,730
This is fairly straightforward using Java generics. You can replace the actual class User
, Event
, etc. with a type parameter.
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();
}
Then do the same for the implementation:
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...
}
Even further, you can also create your actual services as:
@Service
class UserService extends GenericService<User> { }
@Service
class EventService extends GenericService<Event> { }
Here's a good tutorial from the Java documentation: Learning the Java Language: Generics
Another one with good examples: The Basics of Java Generics
Author by
Luis-Orlando Guzman
Updated on June 06, 2022Comments
-
Luis-Orlando Guzman almost 2 years
I have many services that have repeated code and I want to know how to implement a generic service so all my services can extend it.
Service interfaces example (Repeated code):
@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(); }
And their implementations (Now, I have the same code in all the implementations):
@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... }
-
Robert Moskal almost 6 yearsDoes this approach actually deduplicate the code at all?
-
metacubed almost 6 years@RobertMoskal, hmm, I'm not sure what you mean. It does deduplicate User vs Event services. And I'm sure the real code is much more complex.
-
metacubed almost 6 years@RobertMoskal, I'll clarify the answer a bit more. Thanks!