2011-11-24 4 views
0

는 원래이 스레드에 따라 :스프링의 IoC와 일반 인터페이스 유형 구현

Spring IoC and Generic Interface Type

이 하나

Write Less DAOs with Spring Hibernate using Annotations

나는의 이전 아이디어의 구현에 접근하는 방법을 궁금하네요. 내가 가지고 있다고 말하자.

@Repository 
@Transactional 
public class GenericDaoImpl<T> implements GenericDao<T> { 

    @Autowired 
    private SessionFactory factory; 
    private Class<T> type; 

    public void persist(T entity){ 
     factory.getCurrentSession().persist(entity); 
    } 

    @SuppressWarnings("unchecked") 
    public T merge(T entity){ 
     return (T) factory.getCurrentSession().merge(entity); 
    } 

    public void saveOrUpdate(T entity){ 
     factory.getCurrentSession().merge(entity); 
    } 

    public void delete(T entity){ 
     factory.getCurrentSession().delete(entity); 
    } 

    @SuppressWarnings("unchecked")  
    public T findById(long id){ 
     return (T) factory.getCurrentSession().get(type, id); 
    } 

} 

나는 O.K이다. 마커 인터페이스를 갖는 :

public interface CarDao extends GenericDao<Car> {} 
public interface LeaseDao extends GenericDao<Lease> {} 

그러나 내가 1 GenericDaoImpl을 통해 구현 세부 사항을 깔때기 할 서면 간단한 CRUD에 대한 IMPL (들)을 중복 방지하기 위해 (위 같은 것을하는 것은 GenericDaoImpl입니다). (나는 고급 DAO의 기능을 필요로 엔티티에 대한 사용자 정의 IMPL (들)을 작성합니다.)

그럼 결국 내가 할 수있는 내 컨트롤러에서 :

CarDao carDao = appContext.getBean("carDao"); 
LeaseDao leaseDao = appContext.getBean("leaseDao");  

이 가능합니까? 이것을 달성하기 위해 내가해야 할 일은 무엇입니까?

+2

'@Repository CarDaoImpl extends GenericDaoImpl '과'@Repository LeaseDaoImpl extends GenericDaoImpl '두 클래스를 만들 수 없습니까? 이로써 모든 구현 세부 사항이 상위 클래스에 있습니까? 아니면 뭔가 빠졌습니까? – matsev

+0

왜 내가 어제 그 생각을하지 않았는지 모르겠다. – sloven

답변

1

인터페이스는 클래스를 확장 할 수 없으므로이 경우 마커 인터페이스를 사용할 수 없습니다. 당신은 수업을 가질 수 있습니다. 현재 양식에서는 GenericDAOImpl을 확장 할 수있는 특정 클래스의 클래스를 작성해야하므로 GenericDAOImpl 빈을 작성할 수 있다고 생각하지 않습니다. 즉, sessionfactory를 정적 필드로 별도의 클래스로 끌어 와서 유선 연결하고 DAO에서 정적 참조를 사용할 수 있습니다. 그런 다음, 전체 DAO를 연결하지 않고 새로운 GenericDAOImpl() (또는 공장을 통해) 인스턴스를 생성하면 작동합니다. 분명히 특정 작업을 위해 GenericDAOImpl을 확장 한 구현을 가질 수 있습니다.

HTH!