Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new to CDI, tried to find solution for this question, but, couln't found any. Question is Suppose I have one class which is being injected(A) from, where some value(toPass) is getting injected, now I want to pass this same value(toPass) to class B, which is getting injected from class A.

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

    @Inject
    private B b;
}

public class B 
{
    private String toPass; 
    public B(String toPass)
    {
        toPass = toPass;
    }
}

Can anybody please help me in this? Note: we cannot initialize the toPass variable of B in the same way as we have initialized in A, there is some restriction to it. Basically in Spring we could have done it easily, but, I wanted to do it in CDI.

like image 546
Krishna Kumar Avatar asked Oct 10 '15 08:10

Krishna Kumar


2 Answers

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.

like image 107
A.Panzer Avatar answered Nov 07 '22 12:11

A.Panzer


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);
   }
}
like image 35
Matej Briškár Avatar answered Nov 07 '22 12:11

Matej Briškár