Rafael Paulino
Rafael Paulino

Reputation: 581

Do I have to annotate class when using CDI Events @Observes?

I create a class to observe an event.

Do I NEED to annotate this class with @Singleton? Or @Startup to force it listening when the application is up?

Or is it just enough to create a class, annotate the method with @Observes and it is done?

Upvotes: 0

Views: 443

Answers (2)

Georg Leber
Georg Leber

Reputation: 3605

If you look into the specs in chapter 10.3. Observer resolution it is defined:

An event is delivered to an observer method if:
- The observer method belongs to an enabled bean. [...]

So what is a bean, according to the spec 3.1.1. Which Java classes are managed beans?:

A Java class is a managed bean if it meets all of the following conditions:
- It is not an inner class.
- It is a non-abstract class, or is annotated @Decorator.
- It does not implement javax.enterprise.inject.spi.Extension.
- It is not annotated @Vetoed or in a package annotated @Vetoed.
- It has an appropriate constructor - either:
the class has a constructor with no parameters, or
the class declares a constructor annotated @Inject.

If your class meets this conditions and you have set the bean-discovery-mode in your beans.xml to "all", you don't need to annotate your class. If the bean-discovery-mode is set to annotated, your class must have at least the @Dependent annotation.

Upvotes: 2

Siliarus
Siliarus

Reputation: 6753

First of all @Startup is an EJB annotation, not CDI. Likewise, @Singleton can be EJB annotation (there is CDI one as well, but behaves a tad bit differently than what you may expect).

With that said, let's move on to the real question. The discovery of observer method mandates that it is present on a CDI bean. So you can refer to what is CDI bean and when is such a bean found. With a bit of reading in CDI spec you will find out that this depends on bean discovery mode. If you have mode all, where every class will be a candidate for a bean (@Dependent one if not annotated with other scope), your observers will be found and picked up.

However, you may choose to use bean discovery mode annotated, where only classes with so called bean defining annotations classify as beans. In such a case, if there is observer on a method with no bean defining annotation, it will not be detected.

In short, if you always use some scope on the class which has an observer, you are safe.

Upvotes: 1

Related Questions