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

时间:2021-03-28 18:57:32

I've tried putting the remote interface of another Singleton bean into another. However, the remote object will always be null. Is there any other way I could get around it?

我已经尝试将另一个Singleton bean的远程接口放到另一个。但是,远程对象将始终为null。还有其他方法可以解决它吗?

@Singleton
public class SingletonBean1 implements SingletonBean1Remote {

    @EJB
    SingletonBean2Remote singletonBean2Remote;

    ...

    public SingletonBean1() {
        ...

        singletonBean2Remote.anyMethod(); // returns NullPointerException

        ...
    }

}

2 个解决方案

#1


0  

The fact that it's a Singleton is immaterial. You have to initialize that reference to point to something besides null. As written, that's exactly what should happen.

这是一个单身人士的事实并不重要。您必须初始化该引用以指向除null之外的内容。如上所述,这正是应该发生的事情。

The method that creates singleton #1 should get a reference to singleton #2.

创建单例#1的方法应该获得对单例#2的引用。

#2


0  

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

#1


0  

The fact that it's a Singleton is immaterial. You have to initialize that reference to point to something besides null. As written, that's exactly what should happen.

这是一个单身人士的事实并不重要。您必须初始化该引用以指向除null之外的内容。如上所述,这正是应该发生的事情。

The method that creates singleton #1 should get a reference to singleton #2.

创建单例#1的方法应该获得对单例#2的引用。

#2


0  

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