Why declare always Interfaces for DAO

2019-08-21 07:24发布

问题:

Why we have always to declare first a interface to implement our DAO classes like this

Interface :

public interface IRegion<T extends Serializable> {

    List<T> findAll();

}

DAO Class :

@Transactional
@Repository
public class RegionDAO  implements IRegion < Region > {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Region> findAll() {

        return  sessionFactory.getCurrentSession().createQuery("from Region").list();
    }

}

Controller :

@Controller
public class welcome {

    @Autowired
    private IRegion<Region> regionI;
        ....

}

But it works also when I keep just my DAO class and I remove the interface

@Repository
@Transactional
public class RegionDAO {

    @Autowired
    private SessionFactory sessionFactory;


    public List<Region> findAll() {

        return  sessionFactory.getCurrentSession().createQuery("from Region").list();
    }

}

Controller:

@Controller
public class welcome {

@Autowired
private RegionDAO regionDAO;
        ....

}

So why we have to add interfaces ?