Search code examples
javajavabeanscdicode-injection

EJB CDI injection in non-bean object?


I have

@Named("bean1")
@javax.enterprise.context.SessionScoped
public class Bean1 implements Serializable {
    // ...
}

@Named("bean2")
@javax.enterprise.context.SessionScoped
public class Bean2 implements Serializable {
    private SomeClass object = new SomeClass();
}

and

public class SomeClass {
    @Inject
    private Bean1 injBean;
}

My questions:

1) Bean2 is session scoped. Which scope does Bean2.object have?
2) Why does the injection in someClass not work? Thanks.


Solution

  • 1) Bean2 is session scoped. Which scope does Bean2.object have?

    Well, Bean2.object is just an object inside a Bean2 instance and thus doesn't have any CDI scope.

    2) Why does the injection in someClass not work? Thanks.

    There are at least two reasons:

    • someClass (btw, check the naming conventions) is not a CDI managed bean
    • The object referenced by Bean2.object is not created by CDI and thus CDI doesn't even know that instance exists.

    To fix that, make someClass a managed bean and let CDI inject an instance into Bean2.object.