StuPointerException
StuPointerException

Reputation: 7267

CDI injection of beans with no scope

We have a CDI project using:

In the beans.xml file of the webapp the discovery mode is configured to the recommended setting: bean-discovery-mode="annotated". Despite this I am able to inject this class, which isn't annotated with a scope:

public class TestClass implements Serializable {
    public String getDescription() {
        return "This is a test class";
    }
}

Into this ViewScoped class without any issues:

@ViewScoped
@Named
public class AuthenticationWebBean implements Serializable {

    @Inject
    private TestClass testClass;

I would have expected this to either throw an exception, or to leave the field as null. What is happening here, and will the injected Object take the same scope as the object it's injected into?

Thanks in advance.

Upvotes: 0

Views: 1643

Answers (2)

John Ament
John Ament

Reputation: 11733

The behavior you're describing is in CDI 1.1/1.2, Java EE 7 compliant containers would follow it.

You're using TomEE 1.7.2, which is Java EE 6/CDI 1.0 compliant. It's going to operate under the rules of CDI 1.0 which makes everything a CDI component.

TomEE 7 would begin to demonstrate the behavior you're describing.

Upvotes: 3

Ondro Mihályi
Ondro Mihályi

Reputation: 7760

TomEE normally supports only Java EE 6, only night builds support Java EE 7. bean-discovery-mode="annotated" is only supported in Java EE 7. It means that in TomEE it is most probably ignored and then all beans are considered for injection. If you want to exclude a bean from injection, annotate it with @Alternative. Otherwise the bean would be injected with the same scope as the bean it is injected into. This is equivalent to @Dependent scope, which is default.

Upvotes: 2

Related Questions