How to pass parameter to injected class from another class in CDI?

∥☆過路亽.° 提交于 2019-12-05 10:35:11

You have options:

1. Set toPass variable to b from @PostConstruct method of bean A:

@PostConstruct
public void init() {
    b.setToPass(toPass);
}

or

2. Create producer for toPass variable and inject it into bean A and B.

Producer:

@Produces
@ToPass
public String produceToPass() {
    ...
    return toPass;
}

Injection:

@Inject
@ToPass
String toPass; 

or

3. If bean A is not a dependent scoped bean you can use Provider interface to obtain an instance of bean A:

public class B  
{
    @Inject
    Provider<A> a;

    public void doSomeActionWithToPass() {
        String toPass = a.get().getToPass());
        ...
    }

But you should not use toPass from constructor or from @PostConstruct method.

I need to say before that injection happens just after the object is created and therefore in case toPass is going to change during the life of A object, this change will not have any effect on the already injected B object.

(It would be probably possible to overcome this with some hacky things like creating your own producer method and producing some kind of proxy that would lazily initialize the B instance... But that would be probably not nice )

public class A 
{
   String toPass = "abcd"; // This value is not hardcoded
   private B b;

   @Inject
   public void setB(B b) {
       this.b = b;
       b.pass(toPass);
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!