Spring 4.1.5.RELEASE无法对Hibernate 4.3.8.Final的SessionFactory进行依赖注入
作者:互联网
问题并不重复,因为涉及Hibernate
由于詹姆斯的回答部分解决了这个问题,我接受了它并提出了一个新问题,请跟进here
我试图将SessionFactory注入存储库类;但是,它看起来不起作用,因为代码返回NullPointer异常.
我清理并重建了项目,但问题仍然存在.我也将@Autowired放在setSessionFactory方法上,但没有帮助.
接口
public interface TestRep {
public void get(int id);
}
类
@Repository
public class TestRepImpl implements TestRep{
@Autowired
SessionFactory sessionFactory;
public TestRepImpl() {
}
public TestRepImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Transactional
public void get(int id) {
String hql = "from Business where id=" + id;
Query query = sessionFactory.getCurrentSession().createQuery(hql);
....
PR-servlet.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config/>
.....
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="TestRep" class="com.project.repository.TestRepImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
堆栈跟踪
Mar 10, 2015 12:22:21 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [pr] in context with path [/project] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.project.repository.TestRepImpl.get(TestRepImpl.java:39)
at com.project.web.MainController.index(MainController.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:504)
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:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
罐子
MainController
@Controller
public class MainController {
@RequestMapping("/{viewName}.htm")
public String index(@PathVariable(value = "viewName") String viewName) {
System.err.println(viewName);
Test test = new Test();
test.get(1);
if (isValidView(viewName)) {
return viewName;
}
return null;
}
@RequestMapping("/{viewName}/{viewName2}") //suburb/catname
public String index(@PathVariable(value = "viewName") String viewName, Model model) {
System.err.println(viewName);
if (isValidView(viewName)) {
model.addAttribute("viewName",viewName);
return "page";
}
return null;
}
private boolean isValidView(String viewName) {
switch (viewName) {
case "index":
case "aboutus":
return true;
}
return false;
}
}
测试
@Service
public class Test {
public void get(int i){
TestRepImpl test = new TestRepImpl();
test.get(i);
}
}
的hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">12</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.myproject.model.MyTable" />
....
解决方法:
您需要在任何地方使用自动装配,否则您的程序将无法运行. Spring只能自动装配Spring应用程序上下文中存在的bean,这是@Controller,@ Service和@Repository注释应该做的事情.但是,如果没有< context:component-scan base-package =“your.base.package”>,这些注释就毫无意义.在配置XML中标记.
因此,假设您的控制器,服务和DAO都在com.repository包中的某个位置,您需要将此行添加到XML配置中.
<context:component-scan base-package="com.repository"/>
这样做是告诉Spring递归搜索foo.bar.baz包(以及所有子包)中使用@ Controller,@ Service,@ Repository和@Component注释的类,实例化它们的单例实例并使它们符合条件自动装入其他课程.
您还需要修改控制器和服务类以使用@Autowired.如果使用new关键字实例化它们,Spring无法管理您的类.这些bean是单例(只有一个实例应该存在于你的程序中)是有原因的.
您的控制器需要更改如下.
@Controller
public class MainController {
@Autowired
private TestService testService;
@RequestMapping("/{viewName}.htm")
public String index(@PathVariable(value = "viewName") String viewName) {
System.err.println(viewName);
testService.get(1);
if (isValidView(viewName)) {
return viewName;
}
return null;
}
@RequestMapping("/{viewName}/{viewName2}") //suburb/catname
public String index(@PathVariable(value = "viewName") String viewName, Model model) {
System.err.println(viewName);
if (isValidView(viewName)) {
model.addAttribute("viewName",viewName);
return "page";
}
return null;
}
private boolean isValidView(String viewName) {
switch (viewName) {
case "index":
case "aboutus":
return true;
}
return false;
}
}
请注意,您将服务类自动装入控制器.
您的服务类需要实现一个接口. Spring使用接口完成所有这些自动装配魔法.除非您在XML配置中专门创建该类的实例,否则无法自动装配未实现接口的类.
您的服务类需要更改如下:
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestRepDao testDao;
@Transactional
public void get(int i){
testDao.get(i);
}
}
并创建一个名为TestService的接口.
public interface TestService{
public void get(int i);
}
然后你的DAO变成了
@Repository
public class TestRepDaoImpl implements TestRepDao{
@Autowired
private SessionFactory sessionFactory;
public void get(int id) {
String hql = "from Business where id=" + id;
Query query = sessionFactory.getCurrentSession().createQuery(hql);
}
}
它实现了TestRepDao接口:
public interface TestRepDao{
public void get(int id);
}
你也可以删除声明
<bean id="TestRep" class="com.project.repository.TestRepImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
来自您的XML配置.
正如您所看到的,我已经更改了一些类名以更好地适应Spring约定.您的应用程序应该从Controller到Service Class分层到DAO并再次退出.这应该可以帮助您按照我在此处列出的步骤进行操作.
要记住以下几点:
> Spring讨厌新的关键字.如果你发现自己使用它,你可能做错了什么.
> Spring只会在整个应用程序中通过组件扫描获取任何类的任何实例.请勿使用这些类来存储持久数据或状态.这条道路充满了穿线问题,种族条件和充满酸性蜘蛛的坑.
>阅读并重新阅读文档,如果您以前从未使用过Spring,这些概念并不容易.一旦您了解Spring的工作原理以及它如何使用Spring,它就非常易于使用.
> Spring适用于接口.如果你的类没有实现一个接口,那么Spring不能使用AspectJ加载时间编织来代理它,这是另一天的对话,而不是你应该使用的东西,只是刚开始.如果您不知道为什么Spring需要创建对象的代理,则需要重新阅读文档,直到您了解应用程序上下文.
>我将@Transactional注释移动到Service类中.这是因为DAO应该只关注从数据库访问和检索数据,而不必管理与数据库的连接/会话,这是服务类的工作.
>我猜你在点击类似的东西后开始使用new关键字
No qualifying bean of type found for dependency TestService.
这是Spring告诉你它没有可以在任何类上自动连接到TestService字段的bean.听春天告诉你的事情,它会为你节省很多麻烦.
>不要气馁,当我试图学习如何使用Spring时,我遇到了所有这些问题,但是我完成了它并且Spring现在是我的第二天性.
标签:spring,spring-mvc,dependency-injection,hibernate-4-x 来源: https://codeday.me/bug/20191003/1847892.html