NullPointerException com Spring

5 respostas
PaduaAlves

Bom dia pessoal. Estou iniciando os estudos com spring e não estou conseguindo fazera a injeção de dependência funcionar. Sempre recebo um NullPointerExpection quando chamo o método do meu Dao. Minhas aplicação é bem simples. Ela apenas persiste um objeto livro. Seguem as classes e arquivos de configuração

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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>biblioteca</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	<!--Configuração do spring-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!--Servlet que faz o controle das requisições -->
	<servlet>
		<description></description>
		<display-name>ServletController</display-name>
		<servlet-name>ServletController</servlet-name>
		<servlet-class>com.exemplo.biblioteca.controller.ServletController</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>ServletController</servlet-name>
		<url-pattern>/app</url-pattern>
	</servlet-mapping>
</web-app>

applicationContext.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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="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">
        
	<bean id="livroDao" class="com.exemplo.biblioteca.dao.LivroDaoImpl"/>
	<bean id="livroBean" class="com.exemplo.biblioteca.bean.LivroBean">
		<property name="livroDao" ref="livroDao"/>
	</bean>
</beans>

LivroBean, que é a classe na qual deveria ser injetado o meu Dao

package com.exemplo.biblioteca.bean;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.exemplo.biblioteca.dao.LivroDao;
import com.exemplo.biblioteca.dominio.Livro;
import com.exemplo.biblioteca.logica.Logica;

public class LivroBean implements Logica {
	
	private LivroDao livroDao;

	public LivroDao getLivroDao() {
		return livroDao;
	}

	public void setLivroDao(LivroDao livroDao) {
		this.livroDao = livroDao;
	}

	@Override
	public void executa(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Livro livro = new Livro();
		livro.setAutor(request.getParameter("autor"));
		livro.setTitulo(request.getParameter("titulo"));
		livroDao.gravar(livro);

		RequestDispatcher rd = request.getRequestDispatcher("sucesso.jsp");
		rd.forward(request, response);
	}

}
Meu Dao
package com.exemplo.biblioteca.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.exemplo.biblioteca.dominio.Livro;

public class LivroDaoImpl implements LivroDao {
	private EntityManagerFactory emf = Persistence.createEntityManagerFactory("biblioteca");
	private EntityManager em = emf.createEntityManager();
	
	@Override
	public void gravar(Livro livro) {
		EntityTransaction tx = this.em.getTransaction();
		tx.begin();
		em.persist(livro);
		tx.commit();
		em.close();

	}

}

Agradeço ajuda.

5 Respostas

Guitar_Men

Só uma tentativa mas muda o Bean id do seu LivroDaoImpl no applicationContext.xml. Talvez ele se perca com os nomes iguais, eu ja tive um problema parecido com isso…

PaduaAlves

Não deu certo, continua dando NullPointer quando eu chamo livroDao.gravar(livro). Que foda cara, ja vi inúmeros tutorias e não consigo identificar o erro.

fbeli

Aparentemente está certo.
Mas, pra testar.
Coloca em modo debug e os breakpoints onde aparece o erro e nos sets do LivroBean.

Ve se está passando por todos os pontos e o que realmente aparece o problema.

Ve se colocando o listener assim melhora:

&lt;listener&gt; &lt;description&gt;&lt;/description&gt; &lt;display-name&gt;Spring ContextLoaderListener&lt;/display-name&gt; &lt;listener-class&gt; org.springframework.web.context.ContextLoaderListener &lt;/listener-class&gt; &lt;/listener&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/config/application-context.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt;

abraços

PaduaAlves

Cara, eu debuguei e no momento em que a minha aplicação ta subindo, o spring chama do setLivro e passa a referência do objeto, até ai tudo bem, mas na hora em que eu realmente preciso fazer a persistência, o Dao ta nulo.

fbeli

Seus servlets, actions tb tem que estar iniciados por meio do Spring.

Se vc der new em algum serviço o spring não vai resolver o resto.

pra testar, tenta dar o neu usando esse método.

public Object getBean(String bean){
		Object object = null; 
		try{
			String[] locations = {"/WEB-INF/config/application-context.xml"};
			
			XmlWebApplicationContext context = new XmlWebApplicationContext();
			context.setConfigLocations(locations);
			
			
			context.setServletContext(WebContextFactory.get().getHttpServletRequest().getSession().getServletContext());
			context.refresh();
			object = context.getBean(bean);
		}catch(Exception e ){
			e.printStackTrace();
		}
		return object;
	}
Criado 24 de janeiro de 2011
Ultima resposta 24 de jan. de 2011
Respostas 5
Participantes 3