在过去的两天里,我正在学习使用 wildfly swarm 构建微服务的概念,并使用 EJB、JAX-RS、CDI 和 JPA 设置了一个小服务来测试一些 Java EE 功能。该服务正在运行,但仅当我不使用 Main 类并且包装在 pom.xml中设置为war时。
如果我使用 Main 类添加其他部分,则服务无法正确启动,EJB 未部署并在 JNDI 中可用。
启动 JAX-RS 服务的正确方法是什么?
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>microservice-playground</artifactId>
<groupId>cgh</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>user-service</artifactId>
<packaging>war</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>ejb</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jpa</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>cdi</artifactId>
</dependency>
</dependencies>
<build>
<finalName>user-service</finalName>
<plugins>
<plugin>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-plugin</artifactId>
<configuration>
<mainClass>cgh.user.Main</mainClass>
<properties>
<swarm.context.path>${project.build.finalName}</swarm.context.path>
</properties>
</configuration>
<executions>
<execution>
<goals>
<goal>package</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
主类:
public class Main {
public static void main(String[] args) throws Exception {
Swarm swarm = new Swarm();
swarm.start();
JAXRSArchive archive = ShrinkWrap.create(JAXRSArchive.class);
archive.addPackage(Main.class.getPackage());
archive.addAsWebInfResource(new ClassLoaderAsset("META-INF/persistence.xml", Main.class.getClassLoader()),
"classes/META-INF/persistence.xml");
archive.addAllDependencies();
swarm.deploy(archive);
}
}