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...
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With