简体   繁体   中英

EJB interface JNDI lookup

i have an interface

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

a stateless bean that implements it

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

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

a managed bean

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

    @EJB
    private TestService service;

    ...
}

and this 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");
    }

    ...
}

everyting is packed:

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)

since i want to use common.jar inside different applications, i want a lookup based on Testservice interface name, much like i inject @EJB TestService service; in @ManagedBean or @WebServlet

how to achieve this?

a dirty solution is to declare

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

and lookup it from pojo:

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

any better solution will be happily accepted!

Simple method:

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

    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM