EJB接口JNDI查找

时间:2014-02-09 15:40:20

标签: java dependency-injection ejb jndi

我有一个界面

@Local
public interface TestService extends Serializable
{
    public void aMethod();
}

实现它的无状态bean

@Stateless
public class MyappServiceBean implements TestService
{
    private static final long serialVersionUID = 1L;

    @Override
    public void aMethod()
    {
        // do something...
    }
}

托管bean

@ManagedBean
public class MyappBean implements Serializable
{
    private static final long serialVersionUID = 1L;

    @EJB
    private TestService service;

    ...
}

和这个POJO

public class TestPojo implements Serializable
{
    private static final long serialVersionUID = 1L;

    private final TestService service;

    public TestPojo()
    {
        // this works
        // service = (TestService) InitialContext.doLookup("java:global/myapp/MyappServiceBean");

        // this works too
        // service = (TestService) InitialContext.doLookup("java:global/myapp/MyappServiceBean!com.example.common.ejb.TestService");

        // this works again
        // service = (TestService) InitialContext.doLookup("java:app/myapp/MyappServiceBean");

        // how to lookup ONLY by interface name/class ?
        service = (TestService) InitialContext.doLookup("???/TestService");
    }

    ...
}

每件事都包装好:

myapp.war
    |   
    + WEB-INF
        |
        + lib
        |   |
        |   + common.jar
        |       |
        |       - com.example.common.ejb.TestService (@Local interface)
        |       |
        |       - com.example.common.util.TestPojo (simple pojo, must lookup)
        |
        + classes
            |
            - com.example.myapp.ejb.MyappServiceBean (@Stateless impl)
            |
            - com.example.myapp.jsf.MyappBean (jsf @ManagedBean)

因为我想在不同的应用程序中使用common.jar,我希望基于Testservice接口名称进行查找,就像我在@EJB TestService service;中注入@ManagedBean或{{1} }}

如何实现这个目标?

2 个答案:

答案 0 :(得分:2)

一个肮脏的解决方案是声明

@Stateless(name = "TestService")
public class MyappServiceBean implements TestService

并从pojo中查找:

service = (TestService) InitialContext.doLookup("java:module/TestService");

任何更好的解决方案都会被愉快地接受!

答案 1 :(得分:-1)

简单方法:

    private MyappServiceBean getMyappServiceBean() {
    try {
        return InitialContext.doLookup("java:module/MyappServiceBean");
    } catch (NamingException e) {
        logger.error("Failed to look up MyappServiceBean EJB", e);
    }

    return null;
}