注入 bean returns null Java YES

Injection of bean returns null Java EE 8

我问过类似的问题,但答案不是关于注入问题,所以我在将容器从 Tomcat 更改为 Wildfly 后再次遇到这个问题。

我在我的应用程序中使用命令模式,当我使用 command="signin".

我有下一个类:

CommandEnum.java

public enum CommandEnum {

    EMPTY_COMMAND {
        {
            this.command = emptyCommand;
        }
    },
    NAME_GENERATION {
        {
            this.command = nameGenerationCommand;
        }
    },
    NAME_GENERATION_SETTINGS {
        {
            this.command = nameGenerationSettingsCommand;
        }
    },
    SIGNIN {
        {
            this.command = signinCommand; // is it possible?
        }
    };

    @Inject
    @EmptyCommandQualifier
    Command command;
    @Inject
    EmptyCommand emptyCommand;
    @Inject
    NameGenerationCommand nameGenerationCommand;
    @Inject
    NameGenerationSettingsCommand nameGenerationSettingsCommand;
    @Inject
    SigninCommand signinCommand;

    public Command getCommand() {
        return command;
    }
}

Command.java

public interface Command {
    public String execute(HttpServletRequest request, HttpServletResponse response) throws IOException;
}

ActionFactory.java

public class ActionFactory {

    @Inject
    @EmptyCommandQualifier
    private Command command;

    @Inject
    private CommandEnum commandEnum;

    public Command defineCommand(String action) throws IllegalArgumentException {
        if (action == null || action.isEmpty()) {
            return command;
        }
        commandEnum = CommandEnum.valueOf(action.toUpperCase());
        System.out.println(command.toString()) // returns EmtpyCommand object
        command = commandEnum.getCommand();
        System.out.println(commandEnum.toString()); // returns SIGNIN
        System.out.println(command.toString()); //line 28

        return command;
    }

    @Produces
    public static CommandEnum getEmptyCommandEnum()
    {
        return CommandEnum.EMPTY_COMMAND;
    }
}

登录Command.java

@SigninCommandQualifier
public class SigninCommand implements Command {

    @Inject
    private UserEJB userEJB;

    public String execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        User signinUser = new User(email, password);
        User foundUser = userEJB.findUser(signinUser);
        if (foundUser != null) {
            request.setAttribute("passedAuth", true);
            return PagesManager.getProperty("page.nameGeneration");
        } else {
            request.setAttribute("passedAuth", false);
            return PagesManager.getProperty("page.signin");
        }
    }
}

空Command.java

@EmptyCommandQualifier
public class EmptyCommand implements Command {

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        return null;
    }
}

CreativityServlet.java

public class CreativityServlet extends HttpServlet {

    @Inject
    @EmptyCommandQualifier
    private Command command;

    @Inject
    private ActionFactory actionFactory;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String action = request.getParameter("command");
        try {
            command = actionFactory.defineCommand(action);
        } catch (IllegalArgumentException e) {
            request.setAttribute("msg", action + " " + MessageManager.getProperty("message.wrongaction"));
        }
        String page;
        try {
            page = command.execute(request, response);
        } catch (IOException e) {
            page = PagesManager.getProperty("page.error");
        }
        if (page != null) {
            if (page.equals("not redirecting")) {
                return;
            }
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
            dispatcher.forward(request, response);
        } else {
            page = PagesManager.getProperty("page.index");
            request.getSession().setAttribute("nullPage",
                    MessageManager.getProperty("message.nullpage"));
            response.sendRedirect(request.getContextPath() + page);
        }
    }
}

预选赛:

EmptyCommandQualifier.java

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface EmptyCommandQualifier {
}

SigninCommandQualifier.java

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface SigninCommandQualifier {
}

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_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <display-name>creativity</display-name>
    <servlet>
        <servlet-name>Controller</servlet-name>
        <servlet-class>com.creativity.servlet.CreativityServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Controller</servlet-name>
        <url-pattern>/creativity</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>NameGenerator</servlet-name>
        <servlet-class>com.creativity.servlet.GenerateNameServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NameGenerator</servlet-name>
        <url-pattern>/generateName</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

我捕获了下一个异常:

22:16:14,147 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /creativity: java.lang.NullPointerException
        at factory.ActionFactory.defineCommand(ActionFactory.java:28)
        at com.creativity.servlet.CreativityServlet.processRequest(CreativityServlet.java:39)
        at com.creativity.servlet.CreativityServlet.doPost(CreativityServlet.java:33)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:523)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
        at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
        at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
        at io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
        at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
        at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
        at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
        at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
        at io.undertow.servlet.handlers.ServletChain.handleRequest(ServletChain.java:68)
        at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
        at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
        at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:117)
        at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
        at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
        at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
        at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
        at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
        at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
        at io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
        at io.undertow.servlet.handlers.ServletInitialHandler.access0(ServletInitialHandler.java:78)
        at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:133)
        at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:130)
        at io.undertow.servlet.core.ServletRequestContextThreadSetupAction.call(ServletRequestContextThreadSetupAction.java:48)
        at io.undertow.servlet.core.ContextClassLoaderSetupAction.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create[=21=](SecurityContextThreadSetupAction.java:105)
        at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create[=21=](UndertowDeploymentInfoService.java:1530)
        at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create[=21=](UndertowDeploymentInfoService.java:1530)
        at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create[=21=](UndertowDeploymentInfoService.java:1530)
        at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create[=21=](UndertowDeploymentInfoService.java:1530)
        at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create[=21=](UndertowDeploymentInfoService.java:1530)
        at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
        at io.undertow.servlet.handlers.ServletInitialHandler.access[=21=]0(ServletInitialHandler.java:78)
        at io.undertow.servlet.handlers.ServletInitialHandler.handleRequest(ServletInitialHandler.java:99)
        at io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)
        at io.undertow.server.HttpServerExchange.run(HttpServerExchange.java:841)
        at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1348)
        at org.xnio.XnioWorker$WorkerThreadFactory.run(XnioWorker.java:1280)
        at java.lang.Thread.run(Thread.java:748)

我的 EAR 和 EJB 模块的 META-INF 文件夹以及 WAR 模块的 WEB-INF 文件夹中有 beans.xml。

问题的解决方法是什么?

感谢您的评论,正如 的评论中提到的,我知道枚举不是 CDI 管理的,因此注入 returns null。我处理它在 class 中声明枚举并根据切换条件声明 getter 返回命令。它看起来像下一个:

Commands.java

public class Commands {
    public enum CommandEnum {
        EMPTY_COMMAND,
        NAME_GENERATION,
        NAME_GENERATION_SETTINGS,
        SIGNIN,
        LOGOUT,
        LANGUAGE_EDITOR_GET_CULTURES,
        LANGUAGE_EDITOR_GET_DETAILS
    }

    @Inject
    @EmptyCommandQualifier
    EmptyCommand emptyCommand;
    @Inject
    @NameGenerationCommandQualifier
    NameGenerationCommand nameGenerationCommand;
    @Inject
    @NameGenerationSettingsCommandQualifier
    NameGenerationSettingsCommand nameGenerationSettingsCommand;
    @Inject
    @SigninCommandQualifier
    SigninCommand signinCommand;
    @Inject
    @LogoutCommandQualifier
    LogoutCommand logoutCommand;
    @Inject
    @LanguageEditorGetCulturesCommandQualifier
    LanguageEditorGetCulturesCommand languageEditorGetCulturesCommand;
    @Inject
    @LanguageEditorGetLanguageDetailsCommandQualifier
    LanguageEditorGetLanguageDetailsCommand languageEditorGetLanguageDetailsCommand;

    public CommandEnum getCommandEnum(String action) {
        return CommandEnum.valueOf(action.toUpperCase());
    }

    public Command getCommand(CommandEnum commandEnum) {
        switch (commandEnum) {
            case NAME_GENERATION: return nameGenerationCommand;
            case NAME_GENERATION_SETTINGS: return nameGenerationSettingsCommand;
            case SIGNIN: return signinCommand;
            case LOGOUT: return logoutCommand;
            case LANGUAGE_EDITOR_GET_CULTURES: return languageEditorGetCulturesCommand;
            case LANGUAGE_EDITOR_GET_DETAILS: return languageEditorGetLanguageDetailsCommand;
            default: return emptyCommand;
        }
    }
}