Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI not working after migration to Java EE 7

I recently migrated a simple Java EE 6 project to Java EE 7. In detail this means I just changed the dependency from javax:javaee-api:6.0 to javax:javaee-api:7.0 and deployed it to Glassfish 4 instead of Glassfish 3.

Afterwards the application did not work anymore, because CDI could not inject the annoted dependencies.

like image 997
raeffs Avatar asked Jul 09 '13 15:07

raeffs


3 Answers

The problem was, that I did not know that the deployment descriptor and also the default behaviour to find dependencies has changed in Java EE 7.

The new deployment descriptor (beans.xml) has to look like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all" >
</beans>

Important is the attribute bean-discovery-mode, which configures how CDI finds all the dependencies. With setting it to bean-discovery-mode="all", CDI behaves like in Java EE 6.

like image 157
raeffs Avatar answered Nov 17 '22 07:11

raeffs


Setting bean-discovery-mode="all" works, but could also be set to "annotated" depending on how your beans are set up.

Or you could eliminate beans.xml altogether to create an implicit archive. See the Java EE 7 Tutorial section on packaging CDI applications. To use implicit archives, you need a scope-defining annotation on your beans.

like image 23
Ian Evans Avatar answered Nov 17 '22 06:11

Ian Evans


To get rid of the beans.xml file and make your injections work on Glassfish 4, you have to change the packages of the scopes as well:

javax.faces.bean.ApplicationScoped -> javax.enterprise.context.ApplicationScoped
javax.faces.bean.RequestScoped -> javax.enterprise.context.RequestScoped
javax.faces.bean.SessionScoped -> javax.enterprise.context.SessionScoped
javax.faces.bean.ViewScoped -> javax.faces.view.ViewScoped
like image 2
Hildeberto Mendonca Avatar answered Nov 17 '22 08:11

Hildeberto Mendonca