EJB 嵌入式容器 - 依赖注入不起作用?

发布于 2024-11-08 06:51:06 字数 1158 浏览 0 评论 0原文

看一下下面的代码:

@Local
public interface MyService {

    void printMessage();
}

@Stateless
public class MyServiceImpl implements MyService {

    @Override
    public void printMessage() {
        System.out.println("Hello from MyService.");
    }
}

@Stateless
@Named
public class Application {

    @EJB
    public MyService sampleService;

    private static Application getApplication() throws NamingException {
        Properties properties = new Properties();
        properties.setProperty(EJBContainer.APP_NAME, "admin");
        EJBContainer.createEJBContainer(properties); //.getContext();
        Context context = new InitialContext();

        Application application = (Application) context.lookup("java:global/admin/classes/Application");
        return application;
    }

    public static void main(String[] args) throws NamingException {
        Application application = getApplication();
        application.start(args);
    }

    private void start(String[] args) {
        sampleService.printMessage();
    }
}

我希望在 start() 操作时有 simpletService 实例可用,但它等于 null。所有类都是一个项目的一部分(放置在单独的文件中)。我哪里做错了?谢谢你的建议。

Have a look at following code:

@Local
public interface MyService {

    void printMessage();
}

@Stateless
public class MyServiceImpl implements MyService {

    @Override
    public void printMessage() {
        System.out.println("Hello from MyService.");
    }
}

@Stateless
@Named
public class Application {

    @EJB
    public MyService sampleService;

    private static Application getApplication() throws NamingException {
        Properties properties = new Properties();
        properties.setProperty(EJBContainer.APP_NAME, "admin");
        EJBContainer.createEJBContainer(properties); //.getContext();
        Context context = new InitialContext();

        Application application = (Application) context.lookup("java:global/admin/classes/Application");
        return application;
    }

    public static void main(String[] args) throws NamingException {
        Application application = getApplication();
        application.start(args);
    }

    private void start(String[] args) {
        sampleService.printMessage();
    }
}

I expected to have simpletService instance available at start() operation, but it is equal to null. All classes are part of one project (placed in separated files). Where I have made mistake? Thanks for advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看春风乍起 2024-11-15 06:51:06

最后我找到了解决方案。当我将 start() 操作更改为公开时​​,注入开始工作正常。

Finally I have found solution. When I changed start() operation to be public and injection started work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文