简体   繁体   English

Java EE的CDI无法按预期工作

[英]Java EE's CDI doesn't work as expected

Hi everyone I have the following code trying to use CDI 's @produces 大家好,我有以下代码试图使用CDI@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 这是@connect限定符

//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 我正在使用Java EE 7 + GlassFish 4.1.2

NOTE we usually used Glassfish and CDI and it works fine 注意我们通常使用Glassfish和CDI ,它工作正常

so can anyone help And thanks in advance 所以任何人都可以帮助并提前感谢

In CDI > 1.0, if you do not have any beans.xml, CDI only scans annotated classes. 在CDI> 1.0中,如果您没有任何beans.xml,则CDI仅扫描带注释的类。 So CDI does not take into account your ConnectionSupplier class and the producer. 所以CDI没有考虑你的ConnectionSupplier类和生产者。

You have two ways to correct this : 您有两种方法可以解决此问题:

  • Annotate your ConnectionSupplier class (for example with @ApplicationScoped ) 注释您的ConnectionSupplier类(例如使用@ApplicationScoped
  • Add a beans.xml with bean-discovery-mode="all" to tell CDI to scan all classes. 使用bean-discovery-mode="all"添加beans.xml ,告诉CDI扫描所有类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM