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
    @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...

}

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

@Service
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

@Service
class EventService extends GenericService<Event> { }



Ref:
1. https://www.youtube.com/watch?v=27lk2rl5nYA
2. https://stackoverflow.com/questions/51624481/how-to-implement-a-generic-service-class-in-java-spring-boot
3. https://blog.jayway.com/2013/11/03/spring-and-autowiring-of-generic-types/
4. https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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