Search code examples
dependency-injectioncdijava-ee-7

Meaning of bean discovery mode annotated in CDI 1.1


I am migrating an application to Java EE 7 and would like to CDI 1.1. But I don't get the meaning of bean-discovery-mode="annotated". The CDI 1.1 specification is not very helpful. At least I have not found any useful paragraph. Did I miss it?

This example runs perfectly with bean-discovery-mode="all" and injects an instance of LoggingClass:

public class LoggingClass {
    public Logger logger = Logger.getLogger("ALOGGER");

}

@Test
public class MMLoggerProducerIT extends Arquillian {

    @Inject private LoggingClass lc;

}

But if I change from bean-discovery-mode="all" to bean-discovery-mode="annotated" the container is not able to inject an instance into the field lc.

How do I have to annotate LoggingClass to use bean-discovery-mode="annotated" correctly?


Solution

  • As a practical matter, bean-discovery-mode="ALL" turns on scanning of all classes in an archive. This is called an "explicit archive".

    Omitting beans.xml, or setting bean-discovery-mode="ANNOTATED", makes the archive an implicit archive. In this case, the container will scan for beans with annotated scope types.

    This explains why LoggingClass isn't injected when you set bean-discovery-mode="ANNOTATED". As documented in the Java EE 7 Tutorial:

    CDI can only manage and inject beans annotated with a scope type in an implicit archive.

    Edit: so just to be absolutely clear, you need to add a scope type to LoggingClass. So something like this:

    @SessionScoped
    public class LoggingClass {
        public Logger logger = Logger.getLogger("ALOGGER");
    }
    

    In Java EE 7 and CDI 1.1, we removed the requirement to include the beans.xml deployment descriptor to turn on CDI for an archive, bringing CDI 1.1 in line with most other Java EE APIs where deployment descriptors are optional. It also removed the binary on/off nature of including beans.xml or not. You can control which files are scanned by the container with the settings in bean-discovery-mode.

    See the JavaEE tutorial on packaging CDI applications here: http://docs.oracle.com/javaee/7/tutorial/cdi-adv001.htm#CACDCFDE