Jakarta ee 测试DeltaSpike存储库无法注入EntityManager

Jakarta ee 测试DeltaSpike存储库无法注入EntityManager,jakarta-ee,cdi,jboss-weld,deltaspike,Jakarta Ee,Cdi,Jboss Weld,Deltaspike,我正在尝试为DeltaSpike存储库运行一个简单的测试。但是,我无法注入实体管理器。我使用的是位于以下位置的生产商和测试来源: @ApplicationScoped public class EntityManagerProducer { @Produces public EntityManager getEntityManager() { return Persistence .createEntityManagerFactory("pr

我正在尝试为DeltaSpike存储库运行一个简单的测试。但是,我无法注入实体管理器。我使用的是位于以下位置的生产商和测试来源:

@ApplicationScoped
public class EntityManagerProducer {

    @Produces
    public EntityManager getEntityManager() {
        return Persistence
          .createEntityManagerFactory("primary-test")
          .createEntityManager();
    }
}
在测试资源下的META-INF文件夹中,我有一个persistence.xml文件,其中定义了主测试持久性单元:

<persistence version="2.0"
         xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="primary-test" transaction-type="RESOURCE_LOCAL">
        <properties>
            <!-- Configuring JDBC properties -->
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>

            <!-- Hibernate properties -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.format_sql" value="false"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>
然而,当我运行它时,我得到了一个异常:

 WELD-001408 Unsatisfied dependencies for type [EntityManager] with qualifiers [@Default] at injection point [[field] @Inject private com.repository.UserRepositoryTest.entityManager]
My pom.xml依赖于Apache DeltaSpike测试模块和Weld:

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <deltaspike.version>1.8.2</deltaspike.version>
  <weld.version>1.1.10.Final</weld.version>
</properties>

<dependency>
  <groupId>org.apache.deltaspike.modules</groupId>
  <artifactId>deltaspike-test-control-module-api</artifactId>
  <version>${deltaspike.version}</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.apache.deltaspike.modules</groupId>
  <artifactId>deltaspike-test-control-module-impl</artifactId>
  <version>${deltaspike.version}</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.apache.deltaspike.cdictrl</groupId>
  <artifactId>deltaspike-cdictrl-weld</artifactId>
  <version>${deltaspike.version}</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.jboss.weld.se</groupId>
  <artifactId>weld-se-core</artifactId>
  <version>${weld.version}</version>
  <scope>test</scope>
</dependency>

UTF-8
1.8.2
1.1.10.最终版本
org.apache.deltaspike.modules
deltaspike测试控制模块api
${deltaspike.version}
测试
org.apache.deltaspike.modules
deltaspike测试控制模块impl
${deltaspike.version}
测试
org.apache.deltaspike.cdictrl
deltaspike cdictrl焊缝
${deltaspike.version}
测试
org.jboss.weld.se
焊接se型芯
${weld.version}
测试
你知道为什么实体经理不能被注入吗?我不想用阿奎利安

编辑: 当前pom.xml:

<groupId>com.us</groupId>
<artifactId>deltaspike-samples</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>DeltaSpike samples</name>

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <deltaspike.version>1.8.1</deltaspike.version>
  <weld.version>3.0.4.Final</weld.version>
</properties>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.apache.deltaspike.distribution</groupId>
      <artifactId>distributions-bom</artifactId>
      <version>${deltaspike.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
    <dependency>
      <groupId>org.wildfly.bom</groupId>
      <artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
      <version>8.2.2.Final</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-api</artifactId>
    <scope>compile</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-impl</artifactId>
    <scope>runtime</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-api</artifactId>
    <scope>compile</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-impl</artifactId>
    <scope>runtime</scope>
  </dependency>

  <!--Test dependencies-->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-test-control-module-api</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-test-control-module-impl</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.cdictrl</groupId>
    <artifactId>deltaspike-cdictrl-api</artifactId>
    <version>${deltaspike.version}</version>
    <scope>compile</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.cdictrl</groupId>
    <artifactId>deltaspike-cdictrl-weld</artifactId>
    <version>${deltaspike.version}</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <version>2.0</version>
  </dependency>

  <dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-shaded</artifactId>
    <version>3.0.4.Final</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.jboss.spec.javax.annotation</groupId>
    <artifactId>jboss-annotations-api_1.2_spec</artifactId>
    <scope>test</scope>
  </dependency>

</dependencies>
com.us
三角洲梭子鱼样品
1.0-快照
战争
三角洲梭子鱼样品
UTF-8
1.8.1
3.0.4.4最终版本
org.apache.deltaspike.distribution
分发bom表
${deltaspike.version}
聚甲醛
进口
org.wildfly.bom
jboss-javaee-7.0-with-hibernate
8.2.2.最终版本
聚甲醛
进口
爪哇
JavaEEAPI
7
假如
org.apache.deltaspike.core
deltaspike核心api
编译
org.apache.deltaspike.core
德尔塔斯派克核电站
运行时
org.apache.deltaspike.modules
deltaspike数据模块api
编译
org.apache.deltaspike.modules
deltaspike数据模块impl
运行时
朱尼特
朱尼特
4.12
测试
org.apache.deltaspike.modules
deltaspike测试控制模块api
测试
org.apache.deltaspike.modules
deltaspike测试控制模块impl
测试
org.apache.deltaspike.cdictrl
deltaspike cdictrl api
${deltaspike.version}
编译
org.apache.deltaspike.cdictrl
deltaspike cdictrl焊缝
${deltaspike.version}
测试
javax.enterprise
CDIAPI
2
org.jboss.weld.se
焊接se阴影
3.0.4.4最终版本
测试
org.hibernate.javax.persistence
hibernate-jpa-2.1-api
测试
org.jboss.spec.javax.annotation
jboss-annotations-api_1.2_规范
测试

在JavaSE中使用CDI需要将
beans.xml
放入
META-INF
尽管这是可选的,因为JavaEE7

然后,将发现模式设置为带注释的,应该会检测到您的生产者

以下是一个工作配置:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <deltaspike.version>1.8.2</deltaspike.version>
    <weld.version>3.0.4.Final</weld.version>
</properties>
我将使用Lombok和SLF4J:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>
以下是我的CDI生产者,DeltaSpike数据需要它们,并将UUID作为私钥注入:

package fr.fxjavadevblog;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import java.util.UUID;

/**
 * composite of CDI Producers.
 *
 * @author robin
 */
@ApplicationScoped
public class Producers
{
    public static final String UNIT_NAME = "cdi-deltaspike-demo";

    /**
     * produces the instance of entity manager for the application and for DeltaSpike.
     */
    @Produces
    @SuppressWarnings("unused") // just remove the warning, because the field serves as CDI Producer and the IDE cannot detect it.
    private static EntityManager em = Persistence.createEntityManagerFactory(UNIT_NAME).createEntityManager();

    /**
     * produces randomly generated UUID for primary keys.
     *
     * @return UUID as a HEXA-STRING
     *
     */
    @Produces
    @InjectedUUID
    @SuppressWarnings("unused") // just remove the warning, because the method serves as CDI Producer and the IDE cannot detect it.
    public String produceUUIDAsString()
    {
        return UUID.randomUUID().toString();
    }
}
此类使用名为
@injecteduid
的自定义CDI限定符:

package fr.fxjavadevblog;

import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;


import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * CDI Qualifier for UUID Producers
 *
 * @author robin
 */

@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface InjectedUUID 
{
}
以下是我的JPA实体,使用Lombok和CDI注释:

package fr.fxjavadevblog;

import lombok.*;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.*;
import java.io.Serializable;

/**
 * simple JPA Entity, using Lombok and CDI Injected fields (UUID).
 *
 * @author robin
 */

// lombok annotations
@NoArgsConstructor(access = AccessLevel.PROTECTED) // to avoid direct instanciation bypassing the factory.
@ToString(of = {"id","name"})
@EqualsAndHashCode(of="id")

// CDI Annotation
@Dependent

// JPA Annotation
@Entity
public class VideoGame implements Serializable {

    @Id
    @Inject @InjectedUUID // ask CDI to inject an brand new UUID
    @Getter
    private String id;

    @Getter @Setter
    private String name;

    // this field will work as a flag to know if the entity has already been persisted
    @Version
    @Getter
    private Long version;
}
下面是我的实体类的一个简单工厂:

/**
 * simple Factory for creation VideoGame instances populated with UUID, ready to persist.
 * This factory is need to get a proper Entity. Entities must not be created with the "new" operator, but must be build
 * by invoking CDI.
 *
 * @author robin
 */
public class VideoGameFactory
{
    /**
     * creates and brand new VideoGame instance with its own UUID as PK.
     *
     * @return instance of a VideoGame
     */
    public static VideoGame newInstance()
    {
        // ask CDI for the instance, injecting required dependencies.
        return CDI.current().select(VideoGame.class).get();
    }
}
最后但并非最不重要的是,我的实体的DeltaSpike数据响应:

package fr.fxjavadevblog;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Repository;


/**
 * CRUD (and much more) interface, using DeltaSpike Data module.
 *
 * @author robin
 */

@Repository
interface VideoGameRepository extends EntityRepository <VideoGame, String>
{
    // nothing to code here : automatic Repo generated by DeltaSpike
}
Lombok和UUID生成器的使用是可选的


您可以在github上找到完整的代码源代码,并克隆repo:

我在Deltaspike和数据库存储库的Junit5集成测试中遇到了类似的问题。
基本上,当使用Junit5
@Test
注释时,我无法注入存储库。我不得不使用Junit4
@Test
注释作为解决方法。

我添加了这个beans.xml。但是,下一个问题是:java.lang.ClassNotFoundException:org.jboss.weld.events.WeldEvent。当我使用Weld版本2.1.2.Final时,异常是:ClassNotFoundException:javax.transaction.SystemException。有没有办法测试ApacheDeltaspike?试试上面所有的DEP。我将weld se core更改为weld se以获得一个包含DEP的着色jar。仍然不起作用-NoClassDefFoundError:org/apache/deltaspike/cdise/api/CdiContainerLoadertry weld se Shadded而不是weld se。我将制作一个演示项目,我将尽快在GitHub上发布。在pom.xml中是否包含对JPA和Hibernate的依赖?您能否在问题中发布完整的pom.xml。
<dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-api</artifactId>
    <version>${deltaspike.version}</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-impl</artifactId>
    <version>${deltaspike.version}</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.7.1</version>
</dependency>

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.197</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-runner</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.jboss.weld</groupId>
    <artifactId>weld-junit5</artifactId>
    <version>1.2.2.Final</version>
    <scope>test</scope>
</dependency>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19.1</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.0.3</version>
                </dependency>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.0.3</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>
main/java/fr/fxjavadevblog
          +-- VideoGame.java (JPA Entity)
          +-- VideoGameFactory.java
          +-- VideoGameRepository.java (interface)
          +-- InjectedUUID.java (annotation def.)
          +-- Producers.java (produces EntityManager and UUID has string)
    /resources/META-INF
          +-- beans.xml
          +-- persistence.xml

test/java/fr/fxjavadevblog
          +-- VideoGameReposityTest.java (JUnit 5)
    /resources/META-INF
          +-- beans.xml
          +-- persistence.xml
package fr.fxjavadevblog;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import java.util.UUID;

/**
 * composite of CDI Producers.
 *
 * @author robin
 */
@ApplicationScoped
public class Producers
{
    public static final String UNIT_NAME = "cdi-deltaspike-demo";

    /**
     * produces the instance of entity manager for the application and for DeltaSpike.
     */
    @Produces
    @SuppressWarnings("unused") // just remove the warning, because the field serves as CDI Producer and the IDE cannot detect it.
    private static EntityManager em = Persistence.createEntityManagerFactory(UNIT_NAME).createEntityManager();

    /**
     * produces randomly generated UUID for primary keys.
     *
     * @return UUID as a HEXA-STRING
     *
     */
    @Produces
    @InjectedUUID
    @SuppressWarnings("unused") // just remove the warning, because the method serves as CDI Producer and the IDE cannot detect it.
    public String produceUUIDAsString()
    {
        return UUID.randomUUID().toString();
    }
}
package fr.fxjavadevblog;

import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;


import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * CDI Qualifier for UUID Producers
 *
 * @author robin
 */

@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface InjectedUUID 
{
}
package fr.fxjavadevblog;

import lombok.*;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.*;
import java.io.Serializable;

/**
 * simple JPA Entity, using Lombok and CDI Injected fields (UUID).
 *
 * @author robin
 */

// lombok annotations
@NoArgsConstructor(access = AccessLevel.PROTECTED) // to avoid direct instanciation bypassing the factory.
@ToString(of = {"id","name"})
@EqualsAndHashCode(of="id")

// CDI Annotation
@Dependent

// JPA Annotation
@Entity
public class VideoGame implements Serializable {

    @Id
    @Inject @InjectedUUID // ask CDI to inject an brand new UUID
    @Getter
    private String id;

    @Getter @Setter
    private String name;

    // this field will work as a flag to know if the entity has already been persisted
    @Version
    @Getter
    private Long version;
}
/**
 * simple Factory for creation VideoGame instances populated with UUID, ready to persist.
 * This factory is need to get a proper Entity. Entities must not be created with the "new" operator, but must be build
 * by invoking CDI.
 *
 * @author robin
 */
public class VideoGameFactory
{
    /**
     * creates and brand new VideoGame instance with its own UUID as PK.
     *
     * @return instance of a VideoGame
     */
    public static VideoGame newInstance()
    {
        // ask CDI for the instance, injecting required dependencies.
        return CDI.current().select(VideoGame.class).get();
    }
}
package fr.fxjavadevblog;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Repository;


/**
 * CRUD (and much more) interface, using DeltaSpike Data module.
 *
 * @author robin
 */

@Repository
interface VideoGameRepository extends EntityRepository <VideoGame, String>
{
    // nothing to code here : automatic Repo generated by DeltaSpike
}
<?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_2_0.xsd"
       bean-discovery-mode="annotated" version="2.0">
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
    <persistence-unit name="cdi-deltaspike-demo" transaction-type="RESOURCE_LOCAL">

        <class>fr.fxjavadevblog.VideoGame</class>

        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.schema-generation.database.action" value="create"/>
        </properties>

    </persistence-unit>
</persistence>
package fr.fxjavadevblog;

import org.jboss.weld.junit5.EnableWeld;
import org.jboss.weld.junit5.WeldInitiator;
import org.jboss.weld.junit5.WeldSetup;
import org.junit.Assert;
import org.junit.jupiter.api.Test;

import lombok.extern.slf4j.Slf4j;

import javax.inject.Inject;

/**
 * simple test class for the VideoGameRepository, using LOMBOK and WELD.
 *
 * @author robin
 */

@Slf4j
@EnableWeld
class VideoGameRepositoryTest
{
    @WeldSetup // This is need to discover Producers and DeltaSpike Repository functionality
    private WeldInitiator weld = WeldInitiator.performDefaultDiscovery();

    @Inject
    private VideoGameRepository repo;

    @Test
    void test()
    {

        VideoGame videoGame = VideoGameFactory.newInstance();
        videoGame.setName("XENON");
        repo.save(videoGame);
        // testing if the ID field had been generated by the JPA Provider.
        Assert.assertNotNull(videoGame.getVersion());
        Assert.assertTrue(videoGame.getVersion() > 0);
        log.info("Video Game : {}", videoGame);
    }

}