Search code examples
javacdijava-ee-7glassfish-4

Java EE's CDI doesn't work as expected


Hi everyone I have the following code trying to use CDI's @produces

import java.sql.Connection;
import javax.enterprise.inject.Produces;
public class ConnectionSupplier
{

    @Produces
    //@RequestScoped
    @Connect
    public Connection getConnection()
    {
        //get connection from datasource
    }
}

And this is @connect Qualifier

//remove imports

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Connect{}

and here we make injection

import com.seta.history.db.entities.Day;
import java.sql.Connection;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

@RequestScoped
@Named("day")
public class DayController
{

    @Inject
    @Connect
    private Connection connection;
    public void save(Day day)
    {
        //do-save
    }
}

but it gives the following exception

Severe:   Exception during lifecycle processing 
org.glassfish.deployment.common.DeploymentException: CDI deployment                 
failure:WELD-001408: Unsatisfied dependencies for type Connection with     
qualifiers @Connect
at injection point [BackedAnnotatedField] @Inject @Connect private 
com.seta.history.db.controllers.DayController.connection
at 
com.seta.history.db.controllers.
     DayController.connection(DayController.java:0)

I am using Java EE 7 + GlassFish 4.1.2

NOTE we usually used Glassfish and CDI and it works fine

so can anyone help And thanks in advance


Solution

  • In CDI > 1.0, if you do not have any beans.xml, CDI only scans annotated classes. So CDI does not take into account your ConnectionSupplier class and the producer.

    You have two ways to correct this :

    • Annotate your ConnectionSupplier class (for example with @ApplicationScoped)
    • Add a beans.xml with bean-discovery-mode="all" to tell CDI to scan all classes.