Generics – Implementation in Java Spring Boot and Angular (part-3)

In this part, we will see the use of generics in JAVA Spring boot.
For example, you have several packages which serve several functionalities of your project like User Profile, Dashboard, User Event etc.
Each package has a service which does some CURD functionalities.
All services have some common functionalities. Hence, we have lots of repeated code.
To solve this, we can make a generic service so that all other services can extend it.

Lets create a generic service
First create a interface of the generic service

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

Now let’s create the actual generic service which will implement the previous interface

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
    private IDao<T> dao;

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

    public T save(T entity) {

    // Other CRUD methods...


Lets use the generic service
If we have User package and there if we have user service then we can use the generic service like below

class UserService extends GenericService<User> { }

Again, if we have a another package name Event and there if we have a event service then we can reuse the generic service like

class EventService extends GenericService<Event> { }


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s