gpt4 book ai didi

java - spring mvc Autowiring sessionFactory 给出 null 对象

转载 作者:行者123 更新时间:2023-12-02 02:12:10 24 4
gpt4 key购买 nike

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>

我的 Controller 类

   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接口(interface)

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)

我已经在谷歌上搜索了很多,但无法追踪问题,我是 Spring 新手,请帮助我

最佳答案

在 Controller 中我看到这个:

SpringFormLoginDAOInter daoObj=new SpringFormLoginDAOImpl(); 

您必须对 dao 使用 Autowiring 。这就是使用 Spring 的全部要点 - 使用依赖注入(inject)。

要进行的更改:

  1. SpringFormLoginDAOInter类上方添加@Repository
  2. 在 Controller 中使用 Autowiring 的 SpringFormLoginDAOInter 对象,就像在 Dao 类中使用 SessionFactory 一样。

祝你编码愉快!PS:您需要注意命名约定:)

关于java - spring mvc Autowiring sessionFactory 给出 null 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49853121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com