客户端调用EJB错误:javax.naming.NoInitialContextException。

问题描述 投票:0回答:1

从类Main调用我的EJB。

MyService myService = (MyService) ctx.lookup(MyService.class.getName());

给出错误。

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.ejb.calculator.Main.main(Main.java:26)

如何调用我的EJB?

尝试了两种不同的JNDI调用。

JNDI_NAME = "java:global/ejb/MyService";
MyService myService = (MyService) ctx.lookup(JNDI_NAME);

MyService myService = (MyService) ctx.lookup(MyService.class.getName());

代码。

来源链接

https://bitbucket.org/powder366/ejb/src/master/ 

Glassfish命令。

asadmin start-domain --verbose
asadmin stop-domain --verbose 
http://localhost:8080/
http://localhost:4848/common/index.jsf
mvn package
asadmin deploy ejb-1.0-SNAPSHOT.jar

截图:

enter image description hereenter image description here

注意:

我的测试用例与嵌入式容器一起工作,但我不能调用我的外部运行容器。

使用的版本是Java8,EJB3.0,Glassfish5.0.1,Java EE8.0.1。

更新1:添加了deplyoment容器部署时的日志-deploy-log.txt。参见 git remote。

更新2:将工作中的变化推送到git远程。将工作中的修改推送到 git remote。

更新3:将MDB示例推送至git remote。将 MDB 示例推送至 git remote。

java jakarta-ee glassfish ejb jndi
1个回答
2
投票

首先,如果你想从外部客户端访问你的EJB,你需要声明一个远程视图。

由于你的EJB只有 @Local 注解,它只提供本地视图。你应该添加 @Remote 注解。

@Local
@Remote
@Stateless
public class MyService implements IMyService {
    public String getMessage() {
        return "Hello!";
    }
}

全局JNDI名称由以下方式形成。

java:global/[EAR module]/[EJB module]/[EJB name]

在你的例子中,因为没有EAR,所以是:

java:global/ejb-1.0-SNAPSHOT/MyService

这个测试应该是有效的。

Context ctx = new InitialContext();
IMyService myService = (IMyService) ctx.lookup("java:global/ejb-1.0-SNAPSHOT/MyService");
Assert.assertEquals(myService.getMessage(), "Hello!");

UPDATE

你还需要将glassfish客户端库添加到classpath中才能运行Main类。

我最初是用JUnit测试的,它对我来说是有效的,因为项目已经声明了个 test 依赖 glassfish-embeded-all 其中包括glassfish客户端。但IntelliJ并没有添加 test 当运行一个Main类时,你可以改变Main类的范围。

你可以改变 glassfish-embeded-allruntime 或添加一个新的依赖关系。

<dependency>
    <groupId>org.glassfish.main.appclient</groupId>
    <artifactId>gf-client</artifactId>
    <version>5.1.0</version>
    <scope>runtime</scope>
</dependency>
© www.soinside.com 2019 - 2024. All rights reserved.