首页 > 解决方案 > 当我尝试从另一个包访问我的控制器类时,RESTEasy JAX-RS Nullpointer

问题描述

我正在基于基本 BCE 模式设置一个 Maven 项目(在 Java EE 中)。在“边界”包中,我开始使用 RESTeasy 指定几个 JAX-RS API。如果我向这个 API 发送 POST、GET 或其他任何内容,他们应该将请求委托给控制器类,然后控制器类基本上完成所有工作。

但是每当边界(Api)向控制器(服务)发送请求时,我都会遇到 Nullpointer 异常,例如:

2020-07-02T13:45:15.987+0200|Info: Try to post User alexhuckerman
2020-07-02T13:45:15.994+0200|Warning: StandardWrapperValve[Resteasy]: Servlet.service() for servlet Resteasy threw exception
org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
    at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:106)
    at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:372)
    at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:216)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:515)
    at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:259)
    at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:160)
    at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
    at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:163)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:245)
    at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:249)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:60)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:750)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1540)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:119)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:611)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:550)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:114)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:199)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
    at boundary.UserApi.postUser(UserApi.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:167)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
    at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:638)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:504)
    at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:454)
    at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:456)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:417)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:391)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:68)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:488)
    ... 37 more

我的 POM.xml

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wm</groupId>
<artifactId>workflowManager</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>workflowManager Maven Webapp</name>
<url>http://maven.apache.org</url>

<dependencies>

    <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-core -->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-core</artifactId>
        <version>4.5.5.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-client -->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>4.5.5.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-servlet-initializer -->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-servlet-initializer</artifactId>
        <version>4.5.5.Final</version>
    </dependency>
    
        <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.12.1.Final</version>
    </dependency> 


    <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jackson-provider -->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>3.12.1.Final</version>
    </dependency> 
    
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.1.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.ibm.db2/jcc -->
    <dependency>
        <groupId>com.ibm.db2</groupId>
        <artifactId>db2jcc</artifactId>
        <version>1.0.2</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source> <!-- or higher, depending on your project -->
                <target>1.8</target> <!-- or higher, depending on your project -->
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.glassfish.maven.plugin</groupId>
            <artifactId>maven-glassfish-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <glassfishDirectory>C:\Users\AlexanderCimander\Documents\Master@IBM\Uni\glassfish5\glassfish</glassfishDirectory>
                <user>admin</user>
                <passwordFile>files\password.txt</passwordFile>
                <domain>
                    <name>domain1</name>
                    <host>localhost</host>
                    <adminPort>4848</adminPort>
                </domain>
                <components>
                    <component>
                        <name>${project.artifactId}</name>
                        <artifact>${project.build.directory}/${project.build.finalName}.war</artifact>
                    </component>
                </components>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>deploy</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.3.0</version>
            <configuration>
                <archive>
                    <addMavenDescriptor>false</addMavenDescriptor>
                </archive>
                <strong>
                    <archiveClasses>false</archiveClasses>
                </strong>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <executable>C:XXXXX\glassfish5\glassfish\bin\asadmin.bat</executable>
                <arguments>
                    <argument>--host=localhost</argument>
                    <argument>--port=4848</argument>
                    <argument>--user=admin</argument>
                    <argument>--passwordfile=files/password.txt</argument>
                    <argument>--interactive=false</argument>
                    <argument>--echo=true</argument>
                    <argument>--terse=true</argument>
                    <argument>add-resources</argument>
                    <argument>--upload=true</argument>
                    <argument>files/glassfish-resources.xml</argument>
                </arguments>
            </configuration>
        </plugin>

    </plugins>
</build>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

我的 Web.xml

    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>workflowmanager</display-name>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>boundary.ApplicationServlet</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>resteasy.wider.request.matching</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
    <param-name>resteasy.servlet.mapping.prefix</param-name>
    <param-value>/api</param-value>
    </context-param>
</web-app>

我的 Beans.xml(放在 scr/main/webapp/WEB-INF 下)

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

我的应用程序Servlet

    package boundary;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

public class ApplicationServlet extends Application{
    
     private Set<Object> singletons = new HashSet<Object>();
        private Set<Class<?>> classes = new HashSet<Class<?>>();

        public ApplicationServlet() {
            singletons.add(new UserApi());
        }

        @Override
        public Set<Class<?>> getClasses() {
            return classes;
        }

        @Override
        public Set<Object> getSingletons() {
            return singletons;
        }
    
}

我的用户接口

    package boundary;

import java.util.logging.Logger;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import control.UserService;
import entity.User;

@Path("user")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class UserApi{
    
    @Inject
    UserService userService;

    // Create a Logger
    private final static Logger LOGGER = Logger.getLogger(UserApi.class.getName());

    /*
     * Will be called by a Rest-Client. This userApi then redirects the call from the client to the userService.
     * After Processing the call this userApi will then respond to the client.
     * 
     * Example Path to make a call: http://localhost:8080/workflowmanager/api/user/
     */

    /**
     * API method to post an user
     *
     * @param user
     * @return {@link Response} containing the status of the request and (in case of
     *         success) also the requested contract information
     * @throws Exception
     */
    @Transactional(rollbackOn = Exception.class)
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response postUser(@Context final UriInfo uriInfo, @Valid final User user) throws Exception {

        // create User
        LOGGER.info(String.format("Try to post User %s", user.getUsername()));
        final User createdUser = userService.createUser(user);
        LOGGER.info(String.format("User %s successfully created", createdUser.getUsername()));

        return Response.created(null).build();
    }

    /**
     * API method to update an user
     *
     * @param user
     * @return {@link Response} containing the status of the request and (in case of
     *         success) also the requested contract information
     * @throws Exception
     */
    @Transactional(rollbackOn = Exception.class)
    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/{username}")
    public Response putUser(@Context final UriInfo uriInfo, @Valid final User user,
            @PathParam("username") final String userName) throws Exception {

        // avoid change of username
        if (!userName.equals(user.getUsername())) {
            throw new BadRequestException("Not allowed to change username!");
        }

        // update User
        final User updatedUser = userService.updateUser(user);
        LOGGER.info(String.format("User %s successfully updated", updatedUser.getUsername()));

        return Response.ok().build();
    }

    /**
     * API method to get an user
     *
     * @param userName
     * @return {@link Response} containing the status of the request and (in case of
     *         success) also the requested contract information
     * @throws Exception
     */
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/{userName}")
    public Response getUser(@PathParam("userName") final String userName) throws Exception {
        LOGGER.info(String.format("Looking up User %s", userName));
        final User user = userService.getUser(userName);
        return Response.ok(user).build();
    }
    
    /**
       * API method to deregister an user
       *
       * @param username
       * @return  {@link Response} containing the status of the request and (in case of
     *         success) also the requested contract information
       * @throws Exception
       */
      @Transactional(rollbackOn =Exception.class)
      @DELETE
      @Consumes(MediaType.APPLICATION_JSON)
      @Path("/{userName}")
      public Response deleteUser(@PathParam("userName") final String userName) throws Exception {

       userService.deleteContract(userName);
        return Response.noContent().build();
      }
}

我的用户服务

package control;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.ws.rs.NotFoundException;

import entity.User;

@Stateless
public class UserService {
    @PersistenceContext(unitName = "workflowManager")
    EntityManager entityManager;

    // Create a Logger
    private final static Logger LOGGER = Logger.getLogger(UserService.class.getName());

    /*
     * Hier werden die Anfragen von der userApi (Boundary) ankommen und die Daten
     * manipuliert. Ebenfalls wird hier mit der Datenbank gesprochen
     */

    /**
     * Creates a new User
     * 
     * @param user
     * @throws Exception
     */
    public User createUser(final User user) throws Exception {

        // check preconditions
        LOGGER.info(String.format("Checking if user with name %s already exists ", user.getUsername()));
        if (getUser(user.getUsername()) != null) {
            LOGGER.info(String.format("User %s already exists! Persisting process aborted.", user.getUsername()));
            throw new Exception(new InternalError("Something went wrong during the creation of an user"));
        }

        // save
        LOGGER.info(String.format("Creating user with name ", user.getUsername()));
        this.entityManager.persist(user);
        LOGGER.info(String.format("User %s successfully persisted", user.getUsername()));

        return user;
    }

    /**
     * Updates a given user
     *
     * @param user
     * @throws ElcException
     */
    public User updateUser(final User user) throws Exception {
        User existingUser = null;
        final String userName = user.getUsername();
        if (userName != null) {
            LOGGER.info(String.format("Searching for User with userName %s before updating", user.getUsername()));
            existingUser = getUser(userName);
        } else {
            throw new Exception(new InternalError("Something went wrong during the update of an user"));
        }
        user.setId(existingUser.getId());
        LOGGER.info(String.format("Merging user with username ", user.getUsername()));
        final User mergedUser = this.entityManager.merge(user);
        LOGGER.info(String.format("updated username with username %s", user.getUsername()));

        return mergedUser;

    }

    /**
     * Get all available Users as list
     *
     * @return List<User>
     */
    public List<User> getAllUser() throws Exception {
        LOGGER.info("Retrieving all User ...");
        try {
            final List<User> user = this.entityManager.createNamedQuery(User.FIND_ALL, User.class).getResultList();
            return user;
        } catch (Exception e) {
            LOGGER.info(String.format("Getting all users failed %s", e.getMessage()));
            return null;
        }

    }

    /**
     * Gets one user by username
     * 
     * @param username
     * @return
     * @throws Exception
     */
    public User getUser(final String userName) throws Exception {
        // Retrieve contractOwner and check if owner exists.

        LOGGER.info(String.format("try to get user with name %s", userName));

        try {
            // get user
            return this.entityManager.createNamedQuery(User.FIND_BY_USERNAME, User.class)
                    .setParameter("username", userName).getSingleResult();

        } catch (final NoResultException e) {
            // user not found
            LOGGER.info(String.format("No user %s found! Error Message: %s", userName, e.getMessage()));
            throw new NotFoundException();

        } catch (final Exception e) {
            LOGGER.info(String.format("Sorry something went wrong - No user %s found! Error Message: %s", userName,
                    e.getMessage()));
            throw new Exception(new InternalError("Something went wrong while retreiving an user"));
        }

    }
    
    /**
     * Deletes one user by username
     * 
     * @param username
     * @return
     * @throws Exception
     */
     public void deleteContract(final String userName) throws Exception {
            LOGGER.info(String.format("Deleting user %s", userName));
            final User user = getUser(userName);

            try {
            // delete from database
            this.entityManager.remove(user);

            } catch (final Exception e) {
                LOGGER.info(String.format("Sorry something went wrong - user %s could not be deleted! Error Message: %s", userName,
                        e.getMessage()));
                throw new Exception(new InternalError("Sorry something went wrong - user could not be deleted!"));
            }

            LOGGER.info(String.format("User successfully removed.", user.getUsername()));
          }

}

我的用户

    package entity;

import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * The persistent class for the "USER" database table.
 * 
 */
@Entity
@Table(name = "USER")
@NamedQueries({@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"), 
@NamedQuery(name = User.FIND_BY_USERNAME,
query = "SELECT u FROM User u WHERE u.username = :userName")})
public class User implements Serializable {

    static final String PREFIX = "workflowManager.entity.User.";
    public static final String FIND_ALL = PREFIX + "findAll";
    public static final String FIND_BY_USERNAME = PREFIX + "findByUsername";
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "PASSWORD")
    @NotNull(message = "password is required")
    @Size(max = 255, message = "password is too long")
    private String password;

    @Column(name = "ROLE")
    @NotNull(message = "role is required")
    @Size(max = 255, message = "role is too long")
    private String role;

    @Column(name = "USERNAME")
    @NotNull(message = "username is required")
    @Size(max = 255, message = "username is too long")
    private String username;

    // bi-directional many-to-one association to Coderepotarget
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CODEREPOTARGET")
    private Coderepotarget coderepotargetBean;

    // bi-directional many-to-one association to Workflowtooltarget
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "WORKFLOWTOOLTARGET")
    private Workflowtooltarget workflowtooltargetBean;

    public User() {
    }

    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRole() {
        return this.role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Coderepotarget getCoderepotargetBean() {
        return this.coderepotargetBean;
    }

    public void setCoderepotargetBean(Coderepotarget coderepotargetBean) {
        this.coderepotargetBean = coderepotargetBean;
    }

    public Workflowtooltarget getWorkflowtooltargetBean() {
        return this.workflowtooltargetBean;
    }

    public void setWorkflowtooltargetBean(Workflowtooltarget workflowtooltargetBean) {
        this.workflowtooltargetBean = workflowtooltargetBean;
    }

}

更多信息: 在尝试让 userService 完成工作数小时后,我尝试在 UserApi 本身内完成所有逻辑。我将持久性上下文添加到 userApi 并实例化了 EntityManager。当我尝试使用 EntityManager 时,我得到了另一个 NPE。

我使用命令在 glassfish5 上部署应用程序mvn clean install

我还尝试了其他几个命令,例如 Maven->Update Project、mvn clean、project clean,并且我已经多次重新启动 Eclipse 等。

我使用 CDI 1.0 和 Dynamic Webmodule 3.0 但是当我启动服务器时它告诉我(没有更大的问题):

BeforeBeanDiscovery.addAnnotatedType(AnnotatedType<?>) used for class org.glassfish.jersey.ext.cdi1x.servlet.internal.CdiExternalRequestScope is deprecated from CDI 1.1! [..]  

我觉得那里也发生了一些很奇怪的事情?

现在我非常困惑和沮丧,也许你们知道缺少什么。

标签: mavencdiresteasyinjectjava-ee-8

解决方案


好的,谢谢@Nikos 和@mtj!

事实证明,我的 Glassfish 服务器和最新版本的 Resteasy 和 Java 都面临着一些依赖性问题。

经过数小时调试依赖项后,我决定切换到 Jersey。

但是@Nikos 的建议是完全正确的!如果您想使用 ApplicationServlet,请确保使用classes.add(UserApi.class)ApplicationServlet 或将其留空,并希望您的系统能够自行找到它!

例如,Jersey 在控制台中告诉我它找到了哪些类作为 servlet,所以一定要检查日志!:-)


推荐阅读