【问题标题】:@PersistenceContext in Autowired Construcor in SpringSpring中自动装配构造函数中的@PersistenceContext
【发布时间】:2017-10-18 09:27:34
【问题描述】:

我有一个如下所示的服务:

@Service
public class MyService {

private final EntityManager entityManager;

private final SomeBean someBean;

@Autowired
public DbServiceImpl(EntityManager entityManager, SomeBean someBean) {
    this.entityManager = entityManager;
    this.someBean = someBean;
}
}

我需要用@PersistenceContext 注释EntityManager。我该怎么做,同时保留 @Autowired 构造函数? 那么问题来了,我可以单独注释构造函数参数entityManager,同时保留@Autowired注释吗?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    我之前遇到过这个问题,不幸的是我认为您不能使用注解@Autowired 在构造函数中注入EntityManager。看这张票:

    https://jira.spring.io/browse/SPR-10443

    【讨论】:

    • 不幸的是,如果您想使用 Spring DI 和注解注入,唯一的解决方案是在提交的 EntityManager 上使用注解 @PersistenceContext。
    【解决方案2】:

    我不确定您是否需要在构造函数中包含 EntityManager。事实上,你做不到。 可以查看详细解决方案here

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多