@EJB - 注入Servlet需要类型接口,而不是类(bean)

时间:2015-11-12 19:46:40

标签: java servlets dependency-injection annotations ejb

我遇到了这个奇怪的问题,希望有人能澄清一下。

1)我有一个简单的EJB,它由一个接口DemoSessionInterface和一个实现类DemoSesssionBean组成(下面提供的代码)。

2)一个简单的servlet,我注入了上述EJB的实例

@EJB
DemoSessionInterface bean;

如您所见,如果我声明类型为Interface(DemoSessionInterface)的变量bean,那么它可以正常工作。但是,如果我将bean的类型更改为类(bean本身),如下所示:

@EJB
DemoSesssionBean bean;

然后当我部署应用程序时,weblogic会抛出一个错误:

weblogic.management.DeploymentException: weblogic.application.naming.ReferenceResolutionException:
 [J2EE:160200]Error 
resolving ejb-ref "test.MyServlet/bean" from module "web" of application "web".
 The ejb-ref does not have an ejb-link and the JNDI name of the target bean has
 not been specified. Attempts to automatically link the ejb-ref to its target 
bean failed because no EJBs in the application were found to implement the 
"ejb.DemoSessionBean" interface. Link or map this ejb-ref to its target EJB and 
ensure the interfaces declared in the ejb-ref are correct.
    at weblogic.application.internal.flow.ReferenceResolutionFlow.resolveReferences
(ReferenceResolutionFlow.java:42)
    at weblogic.application.internal.flow.ReferenceResolutionFlow.prepare
(ReferenceResolutionFlow.java:31)

所以我需要将bean始终声明为接口,而不是Bean本身?如果我有多个实现DemoSessionInterface的类怎么办?这会引起冲突吗?

======= 代码:

@Local
public interface DemoSessionInterface {
    public String getHelloString();
}


@Stateless//(mappedName = "MrBean")
public class DemoSessionBean implements DemoSessionInterface {
    public DemoSessionBean() {
    }

    @Override
    public String getHelloString(){
        return "Hello there; How are you????";
    }
}

@javax.servlet.annotation.WebServlet(name = "MyServlet", urlPatterns={"/hi"})
public class MyServlet extends HttpServlet {

    @EJB
    DemoSessionInterface bean; 

    protected void doGet(...)

0 个答案:

没有答案