NullPointerException categoriaService- Spring 4

16 respostas
E

Pessoal, estou iniciando o Spring agora, e esta dando o seguinte erro :

SEVERE: Received 'java.lang.NullPointerException' when invoking action listener '#{cadastroClienteBean.cadastrar}' for component 'j_idt8'
Jan 30, 2015 10:36:35 AM javax.faces.event.MethodExpressionActionListener processAction
SEVERE: java.lang.NullPointerException
	at br.com.projetospringjsf.controller.CadastroClienteBean.cadastrar(CadastroClienteBean.java:28)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
	at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
	at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:775)
	at javax.faces.component.UICommand.broadcast(UICommand.java:300)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
	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:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
	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 30, 2015 10:36:35 AM com.sun.faces.context.AjaxExceptionHandlerImpl log
SEVERE: JSF1073: javax.faces.event.AbortProcessingException caught during processing of INVOKE_APPLICATION 5 : UIComponent-ClientId=j_idt7:j_idt8, Message=/LayoutPadrao.xhtml @17,54 actionListener="#{cadastroClienteBean.cadastrar}": java.lang.NullPointerException
Jan 30, 2015 10:36:35 AM com.sun.faces.context.AjaxExceptionHandlerImpl log
SEVERE: /LayoutPadrao.xhtml @17,54 actionListener="#{cadastroClienteBean.cadastrar}": java.lang.NullPointerException
javax.faces.event.AbortProcessingException: /LayoutPadrao.xhtml @17,54 actionListener="#{cadastroClienteBean.cadastrar}": java.lang.NullPointerException
	at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:182)
	at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
	at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:775)
	at javax.faces.component.UICommand.broadcast(UICommand.java:300)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
	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:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)

Segue meu Bean:

@ManagedBean(name = "cadastroClienteBean")
@SessionScoped
public class CadastroClienteBean implements Serializable {

	private static final long serialVersionUID = 1L;

	@Autowired
	private CategoriaService categoriaService;

	// action listener event
	public void cadastrar(ActionEvent event) {
		System.out.println("dfsafdfsad");
		List<Categoria> list = categoriaService.listCategoria();
		System.out.println("dfsafdfsad");

	}

}

Serviço

public interface CategoriaService {
	public List<Categoria> listCategoria();
}

@Service
public class CategoriaServiceImpl  implements CategoriaService{

	@Override
	public List<Categoria> listCategoria() {
		List<Categoria> list = new ArrayList<Categoria>();
		return list;
	}
}

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<!-- @Controller, @Service, @Configuration, etc. -->
	<context:component-scan base-package="br.com.projetospringjsf.controller" />

	<!-- Enables the Spring MVC @Controller programming model -->
	<mvc:annotation-driven />
</beans>

O meu problema esta aqui, o serviço esta vindo como nullo:

@Autowired
	private CategoriaService categoriaService;

16 Respostas

alexfe

O seu CategoriaService e a sua CategoriaServiceImpl estão nesse pacote ? -> br.com.projetospringjsf.controller

E coloque o @Controller em cima do CadastroClienteBean

@Controller @ManagedBean(name = &quot;cadastroClienteBean&quot;) @SessionScoped public class CadastroClienteBean implements Serializable {

E

Alex,

Estou em outro pacote, minha classe de serviço.

Tem que estar no mesmo pacote do Bean ?

alexfe

Não precisa estar no mesmo pacote mas acontece que vc está dizendo para o scpring ler apenas um pacote
Vc deve apontar todos os pacotes que precisam compartilhar a injeção de dependencia

&lt;context:component-scan base-package="br.com.projetospringjsf.controller" /&gt;  
&lt;context:component-scan base-package="br.com.projetospringjsf.pacote2" /&gt;  
&lt;context:component-scan base-package="br.com.projetospringjsf.pacote3" /&gt;  
&lt;context:component-scan base-package="br.com.projetospringjsf.pacote4" /&gt;  
&lt;context:component-scan base-package="br.com.projetospringjsf.pacote5" /&gt;  
&lt;context:component-scan base-package="br.com.projetospringjsf.pacote6" /&gt;  
&lt;context:component-scan base-package="br.com.projetospringjsf.pacote7" /&gt;
E

Alex,

só um duvida básica, em qual xml eu configuro isso ???

alexfe

No mesmo que vc está usando servlet-context.xml
olha a linha 15

E

alex,

@Controller
@ManagedBean(name = "cadastroClienteBean")
@SessionScoped
public class CadastroClienteBean implements Serializable {

e no servlet.xml

<context:component-scan base-package="br.com.projetospringjsf.controller" />
	<context:component-scan base-package="br.com.projetospringjsf.service" />

mas mesmo assim esta dando nullpointer

pode me ajudar ?

obrigado

alexfe

CategoriaService e a sua CategoriaServiceImpl estão em quais pacotes ???

E

Alex

Estao no pacote service

alexfe

o seu arquivo de configuração tem essa linha no final &lt;mvc:annotation-driven /&gt;

mova ela para o começo e adicione essas outras abaixo

&lt;context:annotation-config /&gt;
    &lt;mvc:annotation-driven /&gt;
    &lt;mvc:default-servlet-handler /&gt;
E

alex, ficou assim, mas mesmo assim esta ocorrendo o nullpointer.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:annotation-config />  
    <mvc:annotation-driven />  
    <mvc:default-servlet-handler />  
    
	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<!-- @Controller, @Service, @Configuration, etc. -->
	<context:component-scan base-package="br.com.projetospringjsf.controller" />
	<context:component-scan base-package="br.com.projetospringjsf.service" />
	
	

	<!-- Enables the Spring MVC @Controller programming model -->


</beans>
alexfe

Nao to em frente ao computador agora mas faz assim declara o sevice bean no arquivo do spring

E

alex,

declarar assim :

<context:component-scan base-package=“br.com.projetospringjsf.controller.CadastroClienteBean” />

declarar assim ??

alexfe

<bean id=“categoriaService” class=“aqui vai o caminho completo da classe categoriaServiceImpl” />

E

Alex, ficou dessa forma, mas ainda não resolveu, sera que não esta faltando mais algum xml do spring??

<!-- Scans within the base package of the application for @Components to configure as beans -->
	<!-- @Controller, @Service, @Configuration, etc. -->
	<context:component-scan base-package="br.com.projetospringjsf.controller" />
	<context:component-scan base-package="br.com.projetospringjsf.service" />
	<bean id="categoriaService" class="br.com.projetospringjsf.service" />
alexfe

Assim vc vai ter que estudar muito o Spring a documentação e todo a sua estrutura, funcionamento e conceito, senão vc não irá conseguir, mas vamos lá

essa linha &lt;bean id="categoriaService" class="br.com.projetospringjsf.service" /&gt;

o porque do id categoriaService ? viu que o id é igual a variavel que vc deu ao seu service ? dentro do CadastroClienteBean ?

e mais vc tem a classe CategoriaServiceImpl que implementa CategoriaService é isso que vc tem que dizer ao spring ele trabalha com arquitetura de interfaces e implementações. Então seguinte o padrao de arquitetura a variavel categoriaService é a sua interface apenas com a primeira letra em minusculo resultando no id e o campo de “class” vc declarou apenas o pacote mas não é isso ali vc coloca a classe de implementação de sua interface que é a classe CategoriaServiceImpl

seguinte o padrão eu considero que a sua CategoriaServiceImpl está dentro do pacote br.com.projetospringjsf.service então ficaria assim

&lt;bean id="categoriaService" class="br.com.projetospringjsf.service.CategoriaServiceImpl" /&gt;
E

Obrigado pelas dicas,

vou dar uma olhada aqui

abc

Criado 30 de janeiro de 2015
Ultima resposta 1 de fev. de 2015
Respostas 16
Participantes 2