spring mvc autowired sessionFactory给出null对象

时间:2018-04-16 08:47:24

标签: java spring spring-mvc autowired sessionfactory

spring mvc autowired sessionFactory中的

给出了null对象。但同样的程序对我有用,但这次它没有。请查看我的代码

spring-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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">    

    <!-- Add support for component scanning -->  
    <context:component-scan base-package="com.loveTodo.springPractice" >

  </context:component-scan>   

    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Define Spring MVC view resolver -->  
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />     
    </bean> 
<mvc:resources mapping="/resources/**" location="/resources/" /> 
    <!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false" />
        <property name="user" value="hbstudent" />
        <property name="password" value="hbstudent" /> 

        <!-- these are connection pool properties for C3P0 -->  
        <property name="minPoolSize" value="5" />  
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />   
    </bean>  

    <!-- Step 2: Setup Hibernate session factory --> 
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.loveTodo.springPractice.entity" />  
        <property name="hibernateProperties">  
           <props>  
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>    

    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager" />

</beans>

我的控制器类

   package com.loveTodo.springPractice.controller;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.loveTodo.springPractice.dao.imp.SpringFormLoginDAOImpl;
import com.loveTodo.springPractice.dao.inter.SpringFormLoginDAOInter;
import com.loveTodo.springPractice.entity.StudentLogin;


@RestController
@RequestMapping("/loginController")
public class SpringFormLoginController {

    @RequestMapping(value = "/authencateUser", method={RequestMethod.GET,RequestMethod.POST})
    public String authencateUser(@ModelAttribute("StudentLogin") StudentLogin theStudent) {

        String statusMessage=""; 
        // log the input data
    String username= theStudent.getUserName();
    String pwd= theStudent.getPassword();


    System.out.println(username);

    SpringFormLoginDAOInter daoObj=new SpringFormLoginDAOImpl(); 
    boolean validateUSer= daoObj.authencateUser(username, pwd);

    if(validateUSer)
    {   
        statusMessage="hello"+username;
    }

        return statusMessage;      
    }
}

DAO界面

package com.loveTodo.springPractice.dao.inter;




public interface SpringFormLoginDAOInter 
{


    boolean authencateUser(String userName,String password);

}

和DAO实现类

package com.loveTodo.springPractice.dao.imp;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.loveTodo.springPractice.dao.inter.SpringFormLoginDAOInter;
import com.loveTodo.springPractice.entity.StudentLogin;

@Repository
public class SpringFormLoginDAOImpl implements SpringFormLoginDAOInter 
{
    @Autowired  
    private SessionFactory sessionFactory;
    @Transactional
    @Override
    public boolean authencateUser(String userName, String password)  
    {
        Session currentSession=sessionFactory.getCurrentSession();
        System.out.println(currentSession);   
        boolean userStatus=false;  
        try {    

            if(userName !=null && password !=null)  
            {

                System.out.println("before");
                List<StudentLogin>  list=currentSession.createQuery("from StudentLogin where userName = :userName and password = :password ",StudentLogin.class).setParameter(1, userName)
                        .setParameter(2, password).list();   
                    if(!list.isEmpty())   
                    {         
                        userStatus=true;  
                    }   

                    System.out.println("after");

                    }  
        }  

    catch (Exception e) {
        e.printStackTrace();
    }


        return userStatus;
    }

}

和例外

Apr 16, 2018 2:01:23 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/springPractice] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.loveTodo.springPractice.dao.imp.SpringFormLoginDAOImpl.authencateUser(SpringFormLoginDAOImpl.java:25)
    at com.loveTodo.springPractice.controller.SpringFormLoginController.authencateUser(SpringFormLoginController.java:31)
    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.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    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:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
    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)

我用谷歌搜索了它尝试了很多,但无法追查问题,我是新来的春天请帮帮我

2 个答案:

答案 0 :(得分:2)

在控制器中我看到了:

SpringFormLoginDAOInter daoObj=new SpringFormLoginDAOImpl(); 

你必须使用自动装配dao's。这就是使用Spring的全部要点 - 使用依赖注入。

要做出更改:

  1. @Repository类之上添加SpringFormLoginDAOInter
  2. 在控制器中使用自动装配的SpringFormLoginDAOInter对象,就像在Dao类中使用了SessionFactory一样。
  3. 快乐的编码! PS:您需要注意命名约定:)

答案 1 :(得分:0)

删除此行

SpringFormLoginDAOInter daoObj=new SpringFormLoginDAOImpl(); 

并在控制器中自动装配SpringFormLoginDAOInter