简体   繁体   English

如何在spring中将一个bean注入一组bean?

[英]How to inject one bean to a set of bean in spring?

the dao layer of my application need a hibernate reference. 我的应用程序的dao层需要一个hibernate引用。

so all the dao bean need it. 所以dao bean都需要它。

I config each, I wander if there are a way to inject a bean to a set of bean in spring? 我配置每个,如果有一种方法可以在春天为一组bean注入一个bean,我会徘徊吗? like pointcut expression. 像切入点表达式。

For the Hibernate-specific part of your question, see " Don't repeat the DAO! ". 有关Hibernate特定部分的问题,请参阅“ 不要重复DAO! ”。 The design is as valid today as it was 8 years ago. 该设计与8年前一样有效。 The gist of it is to not repeat your DAO logic. 它的要点是不重复你的DAO逻辑。 Instead, create a generic DAO parent class containing repeated CRUD and session management logic. 而是创建一个包含重复CRUD和会话管理逻辑的通用DAO父类。 It will typically need two type parameters, one for the type of entity it manages, and another for the type of the entity's @Id . 它通常需要两个类型参数,一个用于它管理的实体类型,另一个用于实体的类型@Id

Here's a paste from the article. 这是文章中的粘贴。 This is the interface 这是界面

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);
}

and this is the parent class 这是父类

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()
            }

Or better yet, just use Spring Data JPA . 或者更好的是,只需使用Spring Data JPA

For this you can use autowiring of the bean (Hibernate reference) into your dao layer. 为此,您可以将bean(Hibernate引用)的自动装配用于dao层。 You can use autowiring byName so that one name works with all. 您可以使用自动装配byName,以便一个名称适用于所有。 This is the soul purpose of introducing autowiring so that you do not have to inject them again and again in each bean. 这是引入自动装配的灵魂目的,因此您不必在每个bean中一次又一次地注入它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM