有 Java 编程相关的问题?

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

java如何在同一Jvm中调用Ejb bean?

我想知道在没有Jax-rsweb服务的情况下,我可以通过多少种方式调用ejbbean。我设置了一个EJB3接口/实现,如下所示

用户服务(接口)

package business;

public interface UserService {

    public String doSomething();

}

UserServiceBean(实现)

@Stateless
@Local
public class UserServiceBean implements UserService{

    public UserServiceBean() {
    }

    @Override
    public String doSomething() {
        return "Work done!";
    }

}

我知道的:我知道通过调用我的web服务,我可以获得output : "Work done!" 像这样

RestService(Web服务)

package webservices;

@Path("/service")
public class RestService {

    @Inject
    private UserService userService;

    public RestService() {
        // TODO Auto-generated constructor stub
    }

    @GET
    @Produces(MediaType.TEXT_HTML)
    @Path("/userService")
    public String getUserServiceResponse(String json){
        String response = userService.doSomething();
        return response;
    }

}

我想要什么:我想要一个简单的方法/途径/快捷方式等等,你可以这么说。在没有任何web服务的情况下调用我的EJB bean,以获得我期望的output : "Work done!"

就像我们在java应用程序中使用公共静态void main方法一样。我问的问题很清楚。希望你们都明白了


共 (1) 个答案

  1. # 1 楼答案

    如果我正确地理解了您的请求,您会寻找一种从java主类的容器外部调用EJB的方法吗

    那样的话,你需要

    • 为容器获取具有正确属性的JNDI上下文
    • 在容器中查找对EJB的引用
    • 在上面执行业务方法

    下面是野蝇的一个例子:

    public static void main(String[] args) throws NamingException {
            Properties jndiProps = new Properties();
            jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
            jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
            jndiProps.put("jboss.naming.client.ejb.context", true);
            jndiProps.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
            jndiProps.put(Context.SECURITY_PRINCIPAL, "user");
            jndiProps.put(Context.SECURITY_CREDENTIALS, "xxx");
            Context ctx = new InitialContext(jndiProps);
            MyBeanRemote myBean = (MyBeanRemote) ctx.lookup("/<appname>/<beanname>!<fullqualifiedremoteinterface>");
            myBean.doSomething();
        }
    

    请注意以下几点:

    • 您需要为EJB提供一个远程接口
    • 您可能需要通过WildFly的bin文件夹中的脚本添加应用程序用户
    • 您需要根据需要调整查找字符串,您将在部署期间在WildFly日志中看到它(只需省略名称空间前缀)

    为了完整起见,我在这里提供了完整的答案,学分属于用户theisuru的my own question