JBoss Weld CDI : Inject the same instance in two different Objects

谁说胖子不能爱 提交于 2019-12-11 06:24:54

问题


I have two basis class A and B. B is injected in A. I have a third class C injected in A and B, as follow :

class A {
    @Inject B b;
    @Inject C c;
}

class B {
    @Inject C c;
}

class C {

}

I'd like the instance of C contained in A and in B is the same. I could use a setC() method in B, but that's not at all the philosophia of injection. Should I use Weld scopes ? If yes, how should I do ?

Thanks


回答1:


The solution is simply annotate my classes and injections with @Singleton Annotation

class A {
    @Inject B b;
    @Inject @Singleton C c;
}

class B {
    @Inject @Singleton C c;
}

@Singleton
class C {

}


来源:https://stackoverflow.com/questions/8502836/jboss-weld-cdi-inject-the-same-instance-in-two-different-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!