【问题标题】:Inject Spring Data Repository in EJB在 EJB 中注入 Spring Data Repository
【发布时间】:2015-08-28 22:45:26
【问题描述】:

我正在构建一个在 Weblogic 12c (EE 6) 中运行的 Web 项目,它是一个 Web 应用程序,我已将项目配置为:

JSF 2 + EJB 3 + Spring 数据

我有一些这样的回购:

public interface ColectorRepository extends JpaRepository<PEBTable, Integer>{

    @Query("select t from PEBTable t where t.id >= ?1 and t.id <= ?2")
    public List<PEBTable> findByRange(Integer a, Integer b);    

}

我也有这种方式来调用 EJB 中的 repo,这样调用它没有问题,它工作正常,我喜欢它:

@Stateless
public class PEBGenericParser implements PEBGenericParserLocal {

    @PersistenceContext(unitName = PEBCons.PEB_PU)
    private EntityManager emPeb;

    @Override   
    public List<PEBTable> getData() {       
        JpaRepositoryFactory jrf = new JpaRepositoryFactory(emPeb); 
        ColectorRepository repo = jrf.getRepository(ColectorRepository.class);
        return repo.findAll();
    };

}

我在寻找什么?好吧,我想以某种优雅的方式调用存储库,使用 CDI 注释、Spring 注释或其他避免使用 springs xml(spring-config.xml 等)的东西,我喜欢 Spring 数据,但我更喜欢避免所有那些 xml 配置,并保持我的 persistence.xml 就像我正在做的那样。

我想做,比如:

@Stateless
public class PEBGenericParser implements PEBGenericParserLocal {

    @PersistenceContext(unitName = PEBCons.PEB_PU)
    private EntityManager emPeb;

    @Inject
    private ColectorRepository repo;

    @Override   
    public List<PEBTable> getData() {       
        return repo.findAll();
    };

}

我将不胜感激任何建议。

【问题讨论】:

  • 你不能简单地@Autowire 吗?

标签: java jpa dependency-injection ejb spring-data


【解决方案1】:

要使其在 Java EE 环境中工作,您需要配置 CDI 容器以提供一种访问容器管理的 EntityManager 的方法。

这可以通过以下简单的配置类来完成:

public class CdiConfig {     
    @Produces
    @Dependent
    @PersistenceContext(unitName = "db_unit")
    public EntityManager entityManager;     
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多