[英]How to inject one bean to a set of bean in spring?
我的應用程序的dao層需要一個hibernate引用。
所以dao bean都需要它。
我配置每個,如果有一種方法可以在春天為一組bean注入一個bean,我會徘徊嗎? 像切入點表達式。
有關Hibernate特定部分的問題,請參閱“ 不要重復DAO! ”。 該設計與8年前一樣有效。 它的要點是不重復你的DAO邏輯。 而是創建一個包含重復CRUD和會話管理邏輯的通用DAO父類。 它通常需要兩個類型參數,一個用於它管理的實體類型,另一個用於實體的類型@Id
。
這是文章中的粘貼。 這是界面
public interface GenericDao <T, PK extends Serializable> {
/** Persist the newInstance object into database */
PK create(T newInstance);
/** Retrieve an object that was previously persisted to the database using
* the indicated id as primary key
*/
T read(PK id);
/** Save changes made to a persistent object. */
void update(T transientObject);
/** Remove an object from persistent storage in the database */
void delete(T persistentObject);
}
這是父類
public class GenericDaoHibernateImpl <T, PK extends Serializable>
implements GenericDao<T, PK>, FinderExecutor {
private Class<T> type;
public GenericDaoHibernateImpl(Class<T> type) {
this.type = type;
}
public PK create(T o) {
return (PK) getSession().save(o);
}
public T read(PK id) {
return (T) getSession().get(type, id);
}
public void update(T o) {
getSession().update(o);
}
public void delete(T o) {
getSession().delete(o);
}
// Not showing implementations of getSession() and setSessionFactory()
}
或者更好的是,只需使用Spring Data JPA 。
為此,您可以將bean(Hibernate引用)的自動裝配用於dao層。 您可以使用自動裝配byName,以便一個名稱適用於所有。 這是引入自動裝配的靈魂目的,因此您不必在每個bean中一次又一次地注入它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.