【问题标题】:Spring: Method Injection Lookup How to use it?Spring:方法注入查找如何使用?
【发布时间】:2015-01-30 11:27:08
【问题描述】:

我可以使用方法注入查找 - 与实体类吗?我使用 Spring+JPA+Hibernate。这允许将原型 bean 注入单例 bean。实体 bean 也可以吗?A 是原型范围的 bean。我想将 A(@Entity) 放入范围 = 单例的 B 类(例如 DAO)。谢谢

@Entity
public class A(){

    private String name;
    private String surname;

    ...//get and set
}//A

public interface DAO{
   public void method();
}//DAO

public class DAOImpl implements DAO{
  private A object_a;

  public void method(){
     //In this method I use everytime a new istance of A
  }//method
}//DAOImpl

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    您可以使用@Embedded 来包含您的子bean,并在您的sql 中使用。

    @Entity
    public class User(){
    
        private String name;
    
        @Embedded
        private Address address;
    
        @Bean(scope=DefaultScopes.PROTOTYPE)
        public User() {
        }
    
        ...//get and set
    }
    
    
    @Entity
    public class Address(){
        private String name;
        ...//get and set
    }
    
    public interface UserRepository extends JpaRepository<User, Long> {
        @Query(value = "select u from users u where u.address.name = :addressName")
        List<Blog> findUserByAddress(@Param("addressName") String addressName);
    }
    

    【讨论】:

    • 我想将 scope=prototype 的实体 bean(A) 放入 scope=sigleton 的普通 bean(例如放入 DAO)
    • 您可以在您的类构造函数中添加@Bean(scope=DefaultScopes.PROTOTYPE) 并尝试一下。
    • 我要使用 Lookup 方法注入
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多