有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java EJB参考配置

我目前正在开发我的第一个JavaEE应用程序,并且面临一些注入问题

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

我想在我的DAO类中注入JPA实体管理器。 DAO类被注入服务,服务被注入servlet

  1. 通用DAO接口

    @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. 职位实体的我的服务接口

    @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

我把这个配置放在我的网站上。但是它不起作用

<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>

共 (1) 个答案

  1. # 1 楼答案

    首先,不需要网络。使用@EJB注释进行注入时的xml配置

    其次,由于类型擦除,您不能使用EJB注入泛型类,您无法确定注入的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