Search code examples
eventscdi

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?


Solution

  • 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.