Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a generic service class in java Spring Boot?

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

    }
like image 423
Luis-Orlando Guzman Avatar asked Aug 01 '18 02:08

Luis-Orlando Guzman


1 Answers

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

like image 86
metacubed Avatar answered Nov 15 '22 23:11

metacubed