从另一个CDI bean获得对C​​DI bean的访问 [英] Get access to CDI bean from another CDI bean

查看:94
本文介绍了从另一个CDI bean获得对C​​DI bean的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从另一个请求范围内的CDI bean访问会话范围内的CDI bean.我有:

I have to get access to a session scoped CDI bean from another request scoped CDI bean. I have got:

  • 会话范围内的CDI Bean,该CDI Bean保持登录用户的身份,
  • 请求范围内的CDI bean,它处理当前登录用户实例的一些数据和需求(为此).

当我尝试从请求范围的bean(通过@Inject批注)访问会话范围的bean时,如下所示-我在这一行中得到NullPointerException异常(位于addData方法):

At the moment when I try to get access to the session scoped bean from request scoped bean (through the @Inject annotation) as you see below - I get the NullPointerException exception in this line (which is located in addData method):

String surname=loginController.getCurrentUser().getSurname();

您能告诉我如何解决此问题吗?

Could you tell me how can I fix this issue?

当然,如果我从任何xhtml页面打印例如#{loginController.currentUser.surname},一切正常,但是我需要从bean而不是从xhtml页面进行访问.

Of course, If I print for example: #{loginController.currentUser.surname} from any xhtml pages, everything works but I need access from the bean, not from the xhtml page.

这是登录页面的一部分:

This is a part of login page:

<h:form class="form">               

    <p:growl id="growl" showDetail="false" />

    <h:inputText id="username" value="#{userLogin.username}" label="Username" required="true" requiredMessage="Username: This field is required." title="Enter your username." pt:placeholder="Username" />                     

    <h:inputSecret  id="password" value="#{userLogin.password}" label="Password" required="true" requiredMessage="Password: This field is required." title="Enter your password." pt:placeholder="Password" />                  

    <p:commandButton value="Login" action="#{loginController.login}" update="growl" styleClass="buttonStyle"/>                  

</h:form>

这是一个会话范围的CDI bean:

This is a session scoped CDI bean:

@Named
@SessionScoped
public class LoginController implements Serializable {

    private static final long serialVersionUID = -6322113716363932422L;

    public String login(){      

        if(userService.login(userLogin)){

            currentUser=userService.getCurrnetUser(userLogin.getUsername());

            return "home?faces-redirect=true";          
        }
        else{

            facesContext.addMessage(null, new FacesMessage("Data entered are incorrect"));
            return null;
        }
    }

    public String logout(){

        currentUser=null;

        return "login?faces-redirect=true";
    }

    public boolean isLoggedIn() {

          return currentUser!=null;
    }

    @Produces
    @LoggedIn
    public UserAccount getCurrentUser(){

        return currentUser; 
    }   

    @Inject
    private FacesContext facesContext;

    @Inject
    private UserServiceImpl userService;

    @Named
    @Produces
    @RequestScoped
    private UserAccount userLogin=new UserAccount();

    private UserAccount currentUser;
}

这是一个请求范围内的CDI bean:

This is a request scoped CDI bean:

@Named
@RequestScoped
public class DataServiceImpl implements DataService {

    @Override
    public void addData(String[] data) {

        //Proccess some data

        String surname=loginController.getCurrentUser().getSurname();

        //Proccess some data
    }

    @Inject
    private LoginController loginController;
}

这是一个堆栈跟踪:

18:45:08,968 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-15) #{dataController.send()}: java.lang.NullPointerException: javax.faces.FacesException: #{dataController.send()}: java.lang.NullPointerException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    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.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    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 io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 34 more
Caused by: java.lang.NullPointerException
    at com.system.service.DataServiceImpl.addData(DataServiceImpl.java:24)
    at com.system.controller.DataController.send(DataController.java:97)
    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 javax.el.ELUtil.invokeMethod(ELUtil.java:308)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:415)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 35 more

18:45:08,971 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-15) javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    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.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    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 io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.system.service.DataServiceImpl.addData(DataServiceImpl.java:24)
    at com.system.controller.DataController.send(DataController.java:97)
    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 javax.el.ELUtil.invokeMethod(ELUtil.java:308)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:415)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 35 more

这是另一个CDI bean,其中有一个send方法(我从中调用addData方法),我们可以在stacktrace中看到它:

This is another CDI bean in which is located a send method (from which I call to the addData method) which we can see in the stacktrace:

@Named
@ViewScoped
public class DataController implements Serializable {

    private static final long serialVersionUID = 1383572529241805730L;

    //some methods

    public void send(){

        if(uploadFile==null){

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "The file isn't uploaded", "You should upload a file"));
        }
        else{

            //Sending the data to the database...

            list=new ArrayList<String>();

            //It should be a upload file but for now I add it manually.
            try(Stream<String> stream=Files.lines(Paths.get("F:/VirtualBox/Share/capture20110815.binetflow"))) {            

                list=stream.collect(Collectors.toList());

                int start=0;                
                Pattern pattern=Pattern.compile(",");
                dataService=new DataServiceImpl();

                for (String s : list) {

                    if(start!=0){

                        String[] data=pattern.split(s);

                        dataService.addData(data);
                    }
                    else start++;
                }                           

            } catch (IOException e) {

                e.printStackTrace();
            }       

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "The data has been added.", ""));           
        }
    }

    @Named
    @Produces
    @RequestScoped
    private UserTable userTable=new UserTable();  

    @Inject
    private DataService dataService;

    @Inject
    private FacesContext facesContext;

    @Inject
    private Logger log;

    private UploadedFile uploadFile;
    private List<String> list;
}

推荐答案

我找到了解决方案.逐步操作:

I found the solution. Step by step what I did:

  1. 我从DataServiceImpl bean中删除了LoginController,并向DataController bean中注入了带有@LoggedIn批注的UserAccount:

  1. I deleted the LoginController from the DataServiceImpl bean and I injected the UserAccount with @LoggedIn annotation to the DataController bean:

@Named
@ViewScoped
public class DataController implements Serializable {

    //other fields and methods

    @Inject
    @LoggedIn
    private UserAccount currentUser;
}

您也可以将LoginController注入到DataController bean而不是UserAccount,但是不建议这样做.如果注入UserAccount,效果会更好.

You can also inject the LoginController to the DataController bean instead of the UserAccount but it isn't recommended. You would better if you inject the UserAccount.

我在DataServiceImpl类中创建了addCurrnetUser()方法.该方法的参数是UserAccount对象:

I created the addCurrnetUser() method in the DataServiceImpl class. The parameter of the method is the UserAccount object:

@Named
@RequestScoped
public class DataServiceImpl implements DataService {

    @Override
    public void addCurrentUser(UserAccount currentUser){

        this.currentUser=currentUser;
    }

    @Override
    public void addData(String[] data) {

        //Proccess some data

        String surname=loginController.getCurrentUser().getSurname();

        //Proccess some data
    }

    private UserAccount currentUser;
}

  • 在调用dataService.addData()之前,我在send()方法(位于DataController Bean中)中调用了dataService.addCurrentUser(currentUser).

  • I called dataService.addCurrentUser(currentUser) in send() method (which is located in the DataController bean) before calling dataService.addData().

    您还可能有一个问题:为什么注入的LoginControllerDataServiceImpl bean中返回null而在DataController bean中为什么不返回?查看讨论.您可以在其中找到一些原因.

    You can also have a question: why does the injected LoginController returns null in the DataServiceImpl bean and in the DataController bean not? Look at this discussion. You can find a few reason there.

    这篇关于从另一个CDI bean获得对C​​DI bean的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆