简体   繁体   English

如何从Singleton bean中调用另一个Singleton bean?

[英]How do I call another Singleton bean from a Singleton bean?

I've tried putting the remote interface of another Singleton bean into another. 我试过将另一个Singleton bean的远程接口放入另一个。 However, the remote object will always be null. 但是,远程对象将始终为null。 Is there any other way I could get around it? 还有其他解决方法吗?

@Singleton
public class SingletonBean1 implements SingletonBean1Remote {

    @EJB
    SingletonBean2Remote singletonBean2Remote;

    ...

    public SingletonBean1() {
        ...

        singletonBean2Remote.anyMethod(); // returns NullPointerException

        ...
    }

}

The fact that it's a Singleton is immaterial. 它是一个Singleton的事实并不重要。 You have to initialize that reference to point to something besides null. 您必须初始化该引用以指向除null之外的其他内容。 As written, that's exactly what should happen. 如所写,这正是应该发生的情况。

The method that creates singleton #1 should get a reference to singleton #2. 创建单例#1的方法应该获得对单例#2的引用。

I know this is an old question but dependency injection occurs AFTER the constructor has completed. 我知道这是一个老问题,但是依赖注入会在构造函数完成后发生。 So in the example above the bean will always be null in the constructor 因此,在上面的示例中,bean在构造函数中将始终为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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