簡體   English   中英

生成服務層類

[英]Generifying Service layer classes

我正在嘗試遵循代碼重用最佳實踐。 我有一些常用方法的通用DAO接口:

    public interface DaoInterface<T> {
        T findById(int id);
        //...more methods...
    }

及其實現類:

    public class GenericDao<T> implements DaoInterface<T> {

        @SuppressWarnings("unchecked")
        private final Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

        @Autowired
        protected SessionFactory sessionFactory;

        @Override
        @SuppressWarnings("unchecked")
        public T findById(int id) {
            Session session = sessionFactory.getCurrentSession();
            return (T) session.get(persistentClass, id);
        }

        //...more methods...
    }

然后,我的每個具體實現類都擴展GenericDao並實現其接口。

我的應用程序中也有Service層。 一些服務的方法將其工作完全委派給DAO類。 因此,在每個具體的Service實現中,我都會自動裝配適當的DAO類並調用其方法。 所以現在看起來:

public interface CustomerService {
    Customer findById(int id);
}

和實現:

@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Override
    public Customer findById(int id) {
        return customerDao.findById(id);
    }
}

我的問題是-如何以與DAO相同的方式來生成服務類? 這樣我的具體課程將看起來像:

public class CustomerServiceImpl extends GenericService<Customer> implements CustomerService {
.....
}

問題是我無法在通用服務中自動裝配DAO類:

@Autowired
private GenericDao<T> dao;

這樣我就可以調用dao的方法了。 我應該在構造函數中執行此操作嗎?

還有一個問題-在泛型類或每個實現類中,使用@Transactional注釋方法的正確位置在哪里?

您必須創建一個通用Dao的實例,並在服務層中做出一些決定:

 @Repository
 public class GenericDao implements DaoInterface<T> {
 //The type must be aquired at runtime,otherwise it may not be thread safe

    @Autowired
    protected SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public T findById(int id,Class<?> persistenceClass) {
        Session session = sessionFactory.getCurrentSession();
        return (T) session.get(persistenceClass, id);
    }

    //...more methods...
}

另外,如果您需要良好的通用存儲庫層,請查看Spring Data Jpa

這將僅創建 GenericDao的一個實例。

接下來,您有2個選擇:

  1. 創建滿足您所有需求的單例服務
  2. 為每個實體創建類服務

     abstract class GenericService<T> { @Autowired protected GenericDao dao; @SuppressWarnings("unchecked") protected final Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; @Override public T findById(int id) { return dao.findById(id,persistenceClass); } } 

    現在,您的每一項服務都必須使用提供的持久性類型擴展GenericService,然后工作就完成了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM