Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

CDI ERRO.

Boa tarde, estou usando o CDI. porém quando eu quando faço o meu código atualizar a lista de alunos ele me retorna o erro.

@Named
@ViewScoped
public class AlunoBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Aluno aluno = new Aluno();
    private Endereco endereco = new Endereco();
    private Pais pais = new Pais();
    private Classe classe = new Classe();

    @Inject
    AlunoDao alunoDao;

    @Inject
    MensagemUtil mensagem;

    @Inject
    PaisDao paisDao;

    @Inject
    ClasseDao classeDao;

    @Inject
    RedireciondorPaginas paginas;


    private List<Aluno> alunos = alunoDao.lista(); // aqui faço a minha lista de alunos receber a lista do Dao para atualizar.
    public List<Aluno> getAlunos() {
        if(alunos == null) {
            alunoDao.lista();
        }
        return alunos;
    }
AQUI O METODO QUE ATUALIZA! e embaixo o erro :(
GRAVE: Error Rendering View[/paginas/alunoPesquisa.xhtml]
java.lang.NullPointerException
    at br.com.bercalini.bean.AlunoBean.<init>(AlunoBean.java:49)
    at br.com.bercalini.bean.AlunoBean$Proxy$_$$_WeldSubclass.<init>(Unknown Source)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:119)
    at org.jboss.weld.injection.ProxyClassConstructorInjectionPointWrapper.newInstance(ProxyClassConstructorInjectionPointWrapper.java:84)
    at org.jboss.weld.injection.ConstructorInjectionPoint.invokeAroundConstructCallbacks(ConstructorInjectionPoint.java:92)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:78)
    at org.jboss.weld.injection.producer.AbstractInstantiator.newInstance(AbstractInstantiator.java:28)
    at org.jboss.weld.injection.producer.InterceptorApplyingInstantiator.newInstance(InterceptorApplyingInstantiator.java:62)
    at org.jboss.weld.injection.producer.BasicInjectionTarget.produce(BasicInjectionTarget.java:116)
    at org.jboss.weld.injection.producer.BeanInjectionTarget.produce(BeanInjectionTarget.java:180)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
    at org.jboss.weld.util.bean.IsolatedForwardingBean.create(IsolatedForwardingBean.java:45)
    at com.sun.faces.application.view.ViewScopeContextManager.createBean(ViewScopeContextManager.java:144)
    at com.sun.faces.application.view.ViewScopeContext.get(ViewScopeContext.java:137)
    at org.jboss.weld.context.PassivatingContextWrapper$AbstractPassivatingContextWrapper.get(PassivatingContextWrapper.java:76)
    at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:101)
    at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:742)
    at org.jboss.weld.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:107)
    at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:90)
    at org.jboss.weld.environment.servlet.util.ForwardingELResolver.getValue(ForwardingELResolver.java:49)
    at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:63)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:94)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:137)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:732)
    at org.primefaces.component.api.UIData.getDataModel(UIData.java:759)
    at javax.faces.component.UIData.getRowCount(UIData.java:356)
    at org.primefaces.component.api.UIData.calculateFirst(UIData.java:210)
    at org.primefaces.component.datatable.DataTableRenderer.preRender(DataTableRenderer.java:115)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:83)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:85)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.layout.LayoutUnitRenderer.encodeEnd(LayoutUnitRenderer.java:49)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:509)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

jan 16, 2017 3:47:16 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/escola] threw exception [null] with root cause
java.lang.NullPointerException
    at br.com.bercalini.bean.AlunoBean.<init>(AlunoBean.java:49)
    at br.com.bercalini.bean.AlunoBean$Proxy$_$$_WeldSubclass.<init>(Unknown Source)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:119)
    at org.jboss.weld.injection.ProxyClassConstructorInjectionPointWrapper.newInstance(ProxyClassConstructorInjectionPointWrapper.java:84)
    at org.jboss.weld.injection.ConstructorInjectionPoint.invokeAroundConstructCallbacks(ConstructorInjectionPoint.java:92)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:78)
    at org.jboss.weld.injection.producer.AbstractInstantiator.newInstance(AbstractInstantiator.java:28)
    at org.jboss.weld.injection.producer.InterceptorApplyingInstantiator.newInstance(InterceptorApplyingInstantiator.java:62)
    at org.jboss.weld.injection.producer.BasicInjectionTarget.produce(BasicInjectionTarget.java:116)
    at org.jboss.weld.injection.producer.BeanInjectionTarget.produce(BeanInjectionTarget.java:180)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
    at org.jboss.weld.util.bean.IsolatedForwardingBean.create(IsolatedForwardingBean.java:45)
    at com.sun.faces.application.view.ViewScopeContextManager.createBean(ViewScopeContextManager.java:144)
    at com.sun.faces.application.view.ViewScopeContext.get(ViewScopeContext.java:137)
    at org.jboss.weld.context.PassivatingContextWrapper$AbstractPassivatingContextWrapper.get(PassivatingContextWrapper.java:76)
    at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:101)
    at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:742)
    at org.jboss.weld.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:107)
    at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:90)
    at org.jboss.weld.environment.servlet.util.ForwardingELResolver.getValue(ForwardingELResolver.java:49)
    at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:63)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:94)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:137)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:732)
    at org.primefaces.component.api.UIData.getDataModel(UIData.java:759)
    at javax.faces.component.UIData.getRowCount(UIData.java:356)
    at org.primefaces.component.api.UIData.calculateFirst(UIData.java:210)
    at org.primefaces.component.datatable.DataTableRenderer.preRender(DataTableRenderer.java:115)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:83)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:85)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.layout.LayoutUnitRenderer.encodeEnd(LayoutUnitRenderer.java:49)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:509)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
3 respostas
solução!

Olá Alisson, tudo bem ?

Cara tem alguns pontinhos que podemos discutir, inicialmente o CDI vai instanciar a sua classe, perfeito ?

E nesse ponto todas as referências que vão ser injetadas, estão nulas, e antes que ele possa dar referência a alguma delas você está utilizando o seu dao, que é null. Ai nesse ponto ele quebra com o NullPointer.

Para gente corrigir isso é bem simples, basta não atribuirmos nada ao atributo:

private List<Aluno> alunos;

Agora quando for necessário pegar a lista para a tela, no nosso getter temos que ter o objeto devidamente construído.

Vamos dar uma olhadinha no seu getter :

    public List<Aluno> getAlunos() {
        if(alunos == null) {
            alunoDao.lista();
        }
        return alunos;
    }

Olha que interessante, agora como o sua listagem é nula, a primeira vez que ele for passar aqui cairá no if e quando isso rolar você vai precisar popular a listagem, mas repare que você apenas está indo ao banco de dados e pegando uma lista e não a coloca em lugar nenhum ! :(

    public List<Aluno> getAlunos() {
        if(alunos == null) {
            this.alunos = alunoDao.lista();
        }
        return alunos;
    }

Dessa forma imagino que você deva parar de receber a Exception.

Espero ter ajudado.

Abraços

Muito bem explicado cara. Só fiquei em duvida na parte do.

List<Aluno> alunos;

Aqui é o CDI que ja vai instanciar o meu atributo né? Não precisaria da anotação do CDI? a @inject? Deixei sem anotação e rodou tudo perfeitamente!

Alisson,

Na verdade, quando eu falei em instanciar sua classe, eu falei no próprio ManagedBean. Que depois de o instanciar ele vai pegar todos os atributos anotados com @Inject e vai instanciar essas classes para você.

Nesse ponto seu DAO, está sendo injetado atráves do CDI, mas antes do CDI conseguir injetar e dar uma referência válida, você estava tentando o utilizar para pegar a listagem, o que estava gerando o NullPointer no DAO.

Espero ter deixado mais claro agora !

Abraços