【问题标题】:Conflict beeween JPA @Entity and Spring @Component/@Resource/@ConfigurableJPA @Entity 和 Spring @Component/@Resource/@Configurable 之间的冲突
【发布时间】:2015-07-20 09:33:46
【问题描述】:

我想自动装配一个通过 JPA @Entity 注释的类,所以我添加了 Spring 的 @Component/@Resource/@Configurable 注释,但它不允许我自动装配该类。

是否需要其他注释?

示例是:

@Component
@Entity
@Table
public class Employee{

   @Autowired
   TestService testService;
   ...
}

其中类 TestService@Service 注释。

【问题讨论】:

  • 请求投反对票的人,也请给出理由。
  • 我不是反对者,但您为什么要这样做? Hibernate 应该管理 @Entity 对象的生命周期,而不是 Spring,这是 @Autowired(与其他 bean 注释一起)的用途。
  • 我了解 Predrag,但我有一个要求。
  • 同意 Predrag,你为什么要这么做??有什么好的理由吗?我不是反对者,但一些建议是添加相关代码... :-)
  • @我们是 Borg,我的要求是在成功构建 Entity 时从 webservice 获取数据,以将这个 i Autowired 服务实现到 Entity 类中。

标签: spring hibernate spring-mvc


【解决方案1】:

您可以轻松地做到这一点,创建一个构造函数并将注入的服务作为参数传递:

@Component
@Entity
@Table
public class Employee{

    Employee(TestService testService){

        //Do some work      
    }
   ...
}

现在调用者类..

@Service
public class CallerClass{

   @Autowired   
   TestService testService;

   Employee employee =new Employee(testService);
}

【讨论】:

    【解决方案2】:

    你需要使用@Configurable

    @Entity
    @Table
    @Configurable
    public class Employee{
    
       @Autowired
       TestService testService;
       ...
    }
    

    http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-atconfigurable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2018-10-19
      • 2012-03-20
      • 2016-03-06
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      相关资源
      最近更新 更多