Erro java.lang.NullPointerException em variavel que seria setada pela IOC Spring [RESOLVIDO]

2 respostas
O

Bom dia a todos. Galera, gostaria da ajuda de voces. Ja faz dias que estou tentando configurar o Spring com Struts e usar o Controle de Transacoes, mas, sem sucesso ainda. Gostaria que voces dessem uma analizada na minha estrutura e me mostrem o porque desse erro. Ja postei em varios grupos porem sem sucesso. Estou usando o Struts 1.3, Hibernate 3, Spring 2.5. As minhas classes, stackTrace e arquivos de configuracao estarao abaixo. Obrigado a todos pela ajuda.

Minha interface e classe DAO que ambas extends da minha classe generica
public interface UsuarioDAO extends GenericDAO<Usuario, Long> {
	
	Usuario consultaLoginSenha(String codigo, String senha);
}
public class UsuarioDAOHibernate extends GenericHibernateDAO<Usuario, Long>
		implements UsuarioDAO {

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Usuario consultaLoginSenha(String codigo, String senha) {
		Usuario usuario = new Usuario();

		Query query = this.sessionFactory
				.getCurrentSession()
				.createQuery(
						"from br.com.MGFSuporte.DAO.Usuario as U Where U.codigo like ? and U.senha like ?");
		query.setString(0, codigo);
		query.setString(1, senha);
		usuario = (Usuario) query.uniqueResult();

		return usuario;

	}

}

A minha interface de servico e classe.

public interface UsuarioService {

	Usuario consultaLoginSenha(String codigo, String senha);
}
@Transactional
public class UsuarioServiceImpl implements UsuarioService {

	private UsuarioDAOHibernate usuarioDAO;

	public void setUsuarioDAO(UsuarioDAOHibernate usuarioDAO) {
		this.usuarioDAO = usuarioDAO;
	}

	@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
	public Usuario consultaLoginSenha(String codigo, String senha) {

		return this.usuarioDAO.consultaLoginSenha(codigo, senha);
	}

}
Agora meu arquivo applicationContext e action-servlet 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:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="
     	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref local="dataSource"/>
		</property>
		<property name="mappingResources">
			<list>
				<value>br/com/MGFSuporte/DAO/Cliente.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Usuario.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Contrato.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Aditivo.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Modulo.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/ModuloContratado.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Autorizacao.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.Oracle9Dialect
				</prop>
				<prop key="show_sql">
					true
				</prop>
				<prop key="hibernate.generic statistics">
					true
				</prop>
				<prop key="hibernate.use_sql_comments">
					true
				</prop>
				
			</props>
		</property>
	</bean>	
	
	<!-- Este datasource é gerenciado pelo servidor -->
	<bean id="dataSource"
		class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="java:comp/env/jdbc/MGFSuporte" />
					
	</bean>
	
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref local="sessionFactory"/>
		</property>
			
	</bean>
	
	
	<bean id="clienteDAO" class="br.com.MGFSuporte.DAO.ClienteDAOHibernate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<bean id="usuarioDAO" class="br.com.MGFSuporte.DAO.UsuarioDAOHibernate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	
</beans>
action-servlet.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:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="
     	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	 
	<bean name="/VerificaUsuario"
		class="br.com.MGFSuporte.controller.VerificaUsuarioAction">
		<property name="usuarioService" ref="verificaUserService">
		</property>
	</bean>
	
	<bean name="/SaveInsertCliente"
		class="br.com.MGFSuporte.controller.EditClienteAction">
		<property name="clienteService" ref="clienteService">
			
		</property>
	</bean>
		 
	 <bean id="verificaUserService" class="br.com.MGFSuporte.service.UsuarioServiceImpl">
	 	<property name="usuarioDAO">
	 		<bean id="usuarioDAO" class="br.com.MGFSuporte.DAO.UsuarioDAOHibernate"/>
	 	</property>
	 </bean>
	 <bean id="clienteService" class="br.com.MGFSuporte.service.ClienteServiceImpl">
	 	<property name="clienteDAO">
	 		<bean id="clienteDAO" class="br.com.MGFSuporte.DAO.ClienteDAOHibernate"/>
	 	</property>
	 </bean>
	
</beans>
A minha classe Action do Struts.
public class VerificaUsuarioAction extends DispatchActionSupport {

	private UsuarioService usuarioService;

	public void setUsuarioService(UsuarioService usuarioService) {
		this.usuarioService = usuarioService;
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		ActionErrors errors = new ActionErrors();
		DynaValidatorForm dyna = (DynaValidatorForm) form;
		Usuario usuario = new Usuario();
		
                 usuario = this.usuarioService.consultaLoginSenha(dyna.getString("codigo"),
		 dyna.getString("senha"));
        }
}
E por ultimo o meu StackTrace que fala que meu dao esta null...
2008-04-09 10:16:18,232 [http-8080-Processor24] WARN org.apache.struts.action.RequestProcessor - Unhandled Exception thrown: class java.lang.NullPointerException
2008-04-09 10:16:18,247 [http-8080-Processor24] ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/MGFSuporte].[action] - Servlet.service() for servlet action threw exception
java.lang.NullPointerException
	at br.com.MGFSuporte.DAO.UsuarioDAOHibernate.consultaLoginSenha(UsuarioDAOHibernate.java:19)
	at br.com.MGFSuporte.service.UsuarioServiceImpl.consultaLoginSenha(UsuarioServiceImpl.java:21)
	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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
	at $Proxy5.consultaLoginSenha(Unknown Source)
	at br.com.MGFSuporte.controller.VerificaUsuarioAction.execute(VerificaUsuarioAction.java:44)
	at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
	at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
	at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
	at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
	at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:868)
	at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:663)
	at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
	at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
	at java.lang.Thread.run(Unknown Source)

2 Respostas

_fs

O erro ocorre na linh 13 (de seu post) da classe UsuarioDAOHibernate?

Se sim, é a sessionFactory que está nula?

Se sim, está ocorrendo alguma exceção na inicialização do Spring?

Se não, o setter está sendo chamado?

O

Felipe.
Estive analizando o stack do tomcat e apareceu essa informacao:

2008-04-10 10:22:43,750 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 2008-04-10 10:22:43,796 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured

Mas quando eu fui debugar meu codigo os objetos DataSource e Connection nao ficaram nulos:

Context con = new InitialContext();
Context env = (Context) con.lookup("java:/comp/env");
DataSource data = (DataSource) env.lookup("jdbc/MGFSuporte");
System.out.println(data == null);
String setup = data.toString();
Connection connec = data.getConnection();
System.out.println(connec == null);

Voces podem analizar meu codigo para ver se esta errado?

server.xml

<GlobalNamingResources>

    <!-- Test entry for demonstration purposes -->
    <Environment name="maxExemptions" type="java.lang.Integer" value="30"/>

    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users -->
    <Resource auth="Container" description="DataSource para fornecer o Pool de Conexoes" driverClassName="oracle.jdbc.OracleDriver" maxActive="40" maxIdle="10" maxWait="600000" name="jdbc/MGFSuporte" password="mgfadmin" type="javax.sql.DataSource" url="jdbc:oracle:thin:@localhost:1521:XE" username="mgfsaga"/>
  </GlobalNamingResources>

Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="MGFSuporte" debug="1" reloadable="true"
	docBase="${catalina.home}/server/webapps/MGFSuporte">
	<ResourceLink global="jdbc/MGFSuporte" name="jdbc/MGFSuporte"
		type="javax.sql.Datasource" />
</Context>

web.xml

<resource-ref>
		<description>
			Referencia de Recurso para o Pool de Conexoes
			configurado no arquivo server.xml
		</description>
		<res-ref-name>jdbc/MGFSuporte</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>

Arquivo de configuracao 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:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="
     	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref local="dataSource"/>
		</property>
		<property name="mappingResources">
			<list>
				<value>br/com/MGFSuporte/DAO/Cliente.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Usuario.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Contrato.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Aditivo.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Modulo.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/ModuloContratado.hbm.xml</value>
				<value>br/com/MGFSuporte/DAO/Autorizacao.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.Oracle9Dialect
				</prop>
				<prop key="show_sql">
					true
				</prop>
				<prop key="hibernate.generic statistics">
					true
				</prop>
				<prop key="hibernate.use_sql_comments">
					true
				</prop>
				
			</props>
		</property>
	</bean>	
	
	<!-- Este datasource é gerenciado pelo servidor -->
	<bean id="dataSource"
		class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="java:/comp/env/jdbc/MGFSuporte"/>
	</bean>
	
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref local="sessionFactory"/>
		</property>
			
	</bean>
	
	<!-- Objeto que nos queremos que seja transacional -->
	<bean id="clienteDAO" class="br.com.MGFSuporte.DAO.ClienteDAOHibernate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<bean id="usuarioDAO" class="br.com.MGFSuporte.DAO.UsuarioDAOHibernate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
</beans>

Obrigado…

Criado 9 de abril de 2008
Ultima resposta 10 de abr. de 2008
Respostas 2
Participantes 2