gpt4 book ai didi

java - EJB引用配置

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:23 24 4
gpt4 key购买 nike

我目前正在开发我的第一个 Java EE 应用程序,但遇到了一些注入(inject)问题。

对于我的项目,我使用 JPA、EJB 和 Servlet。到目前为止,我创建了实体、通用 DAO、DAO 实现、服务、servlet 和 jsp 页面。

我想在我的 DAO 类中注入(inject) JPA 实体管理器。DAO 类被注入(inject)到服务中,服务又被注入(inject)到 Servlet 中。

  1. 通用 DAO 接口(interface)

    @Local
    public interface DAO<T> {
    void insert(T item);
    void delete(T item);
    // and so on … }
  2. 通用 DAO 实现

    public class GenericDAO<T> implements DAO<T> {
    @PersistenceContext(unitName = "MyPU")
    private EntityManager entityManager;
    private final Class<T> entityClass;
    public GenericDAO(Class<T> entityClass) {
    this.entityClass = entityClass;
    }
    @Override
    public void insert(T item) {
    entityManager.persist(item);
    }
    // and so on… }
  3. 我的实体的通用 dao 扩展

    @Stateless
    @LocalBean
    public class PositionDAO extends GenericDAO<Position> {
    public PositionDAO() {
    super(Position.class);
    }
    }
  4. 我的职位实体服务接口(interface)

    @Local
    public interface PositionService {
    void addPosition(Position position);
    void updatePosition(Position position);
    // and so on … }
  5. 我的服务实现

    @Stateless
    @LocalBean
    public class PositionServiceImpl implements PositionService {
    @EJB
    private DAO<Position> positionDao;
    @Override
    public void addPosition(Position position) {
    positionDao.insert(position);
    } // and so on…

    @WebServlet(name = "RegisterServlet", urlPatterns = {"/register"})
    public class RegisterServlet extends HttpServlet {
    @EJB
    PositionService positionService;
Cannot resolve reference Local ejb-ref name=online.recruitment.system.service.PositionServiceImpl/positionDao,Local 3.x interface =online.recruitment.system.dao.DAO,ejb-link=null,lookup=,mappedName=,jndi-name=,refType=Session

我将此配置放入我的 web.xml 中,但它不起作用

<ejb-local-ref>
<ejb-ref-name>positionDao</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>online.recruitment.system.dao.DAO</local>
</ejb-local-ref>

最佳答案

首先,当您使用 @EJB 进行注入(inject)时,不需要 web.xml 配置。注释。

其次,由于类型删除,您无法使用 EJB 注入(inject)泛型类,您无法确定注入(inject)的 EJB ( DAO<Position> ) 是否属于预期类型,这将产生 ClassCastException在运行时。

最好按照评论使用 JB Nizet 的建议:

You should define a PositionDao interface extending DAO, and rename your PositionDao to PositionDaoImpl. Then, inject PositionDao rather than DAO. In fact, I would ditch the interfaces and inject the concrete classes dirctly. They don't bring much to the table

关于java - EJB引用配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34501106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com