关于EJB和资源注入的问题

时间:2009-05-19 13:14:34

标签: ejb code-injection

我在让JBoss将环境变量值注入bean时遇到问题。这是我的bean类:

package com.topcoder.test;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.jboss.annotation.ejb.RemoteBinding;

import com.topcoder.test.Test;

public @Stateless(name = "TestBean")
class TestBean implements Test {

    @Resource(name="managerFile")
    private String managerFile;

    public String getManagerFile() {
        return managerFile;
    }

    public String testMethod() {
        String ret = "the value of managerFile in testMethod() is " + getManagerFile();
        return ret;
    }

    @PersistenceContext(unitName = "persistenceUnit", type = PersistenceContextType.TRANSACTION)
    private EntityManager manager;

    @PersistenceContext(unitName = "persistenceUnit", type = PersistenceContextType.TRANSACTION)
    public void setEntityManager(EntityManager manager) {
        this.manager = manager;
    }

    public EntityManager getEntityManager() {
        if (manager == null) {
            throw new IllegalStateException("EntityManager has not been set on DAO before usage");
        }

        return manager;
    }

    @SuppressWarnings("unchecked")
    public List retrieveAll() throws Exception {
        EntityManager em = getEntityManager();

        List result = em.createQuery("FROM TestEntity").getResultList();

        if (result == null) {
            result = new ArrayList();
        }

        return result;
    }

}

我希望JBoss注入managerFile值。这是我的ejb-jar.xml:

<enterprise-beans>
    <session>
        <ejb-name>Test</ejb-name>
        <ejb-class>com.topcoder.test.TestBean</ejb-class>
        <env-entry>
            <env-entry-name>managerFile</env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>com/topcoder/test/TestBean.properties</env-entry-value>
        </env-entry>
    </session>
</enterprise-beans>

但是当我将我的耳朵部署到JBoss时,我收到此错误消息:

09:07:40,495 WARN [ResourceHandler]没有注入managerFile,找不到匹配的enc注入器env / managerFile

我正在运行JBoss 4.2。我做错了什么?

1 个答案:

答案 0 :(得分:1)

确保ejb-jar.xml位于EJB所在的JAR的META-INF /中,而不是EAR的META-INF。

与您的问题无关,您可以删除:

@PersistenceContext
从你的setEntityManager()方法

(你不需要注释它和entityManager字段)