本文介绍了Spring 4.1.5.RELEASE没有为Hibernate 4.3.8.Final的SessionFactory执行依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题并不重要,因为Hibernate涉及



由于James的答案部分解决了这个问题,所以我接受了并提出了一个新问题,请跟进



我正在尝试将SessionFactory注入到存储库类中;然而,它看起来不起作用,因为代码返回NullPointer异常。
我清理并重建项目,但问题仍然存在。我也把@Autowired放在setSessionFactory方法上,但没有帮助。



界面

  public interface TestRep {
public void get(int id);
}

  @Repository 
public class TestRepImpl实现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;
查询查询= sessionFactory.getCurrentSession()。createQuery(hql);
....

pr-servlet.xml / p>

 <?xml version =1.0encoding =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 =dataSourceref =dataSource/>
< property name =configLocationvalue =classpath:hibernate.cfg.xml/>
< / bean>

< tx:注释驱动/>
< bean id =transactionManager
class =org.springframework.orm.hibernate4.HibernateTransactionManager>
< property name =sessionFactoryref =sessionFactory/>
< / bean>

< bean id =TestRepclass =com.project.repository.TestRepImpl>
< constructor-arg>
< ref bean =sessionFactory//>
< / constructor-arg>
< / bean>

StackTrace

  2015年3月10日12:22:21 org.apache.catalina.core.StandardWrapperValve调用
SEVERE:Servlet.service()用于servlet [pr]在上下文中路径[/ project]抛出异常[请求处理失败;嵌套异常是java.lang.NullPointerException]与根本原因
java.lang.NullPointerException
在com.project.repository.TestRepImpl.get(TestRepImpl.java:39)
在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)
在java.lang.reflect.Method.invoke(Method.java:483)
在org.springframework.web.method .support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
在org.springframework.web.servlet .mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
在org.springframework.web.servlet.mvc.method.ann otation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
在org.springframework。 web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
在org.springframework。 web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
在org.springframework.web.servlet。 FrameworkServlet.doGet(FrameworkServlet.java:857)
在javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet。 java:842)
在javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
在org.apache.cata lina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
在org.apache.tomcat.websocket。 server.WsFilter.doFilter(WsFilter.java:52)
在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
在org.apache.catalina.core.ApplicationFilterChain。 doFilter(ApplicationFilterChain.java:208)
在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve。 java:122)
在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
在org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
在org。 apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
在org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:611)
在org.apache.tomcat。 util.net.JIoEndpoint $ SocketProcessor.run(JIoEndpoint.java:314)
在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:617)
在org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)
在java.lang.Thread.run( Thread.java:745)

Jars





MainController

  @Controller 
public class MainController {

@RequestMapping(/ {viewName} .htm)
public String index(@PathVariable(value =viewName)String viewName){
System.err.println(viewName);
测试测试= new Test();
test.get(1);
if(isValidView(viewName)){
return viewName;
}
返回null;
}

@RequestMapping(/ {viewName} / {viewName2})//郊区/ catname
public String index(@PathVariable(value =viewName)String viewName,Model model){
System.err.println(viewName);
if(isValidView(viewName)){
model.addAttribute(viewName,viewName);
返回页;
}
返回null;
}

private boolean isValidView(String viewName){
switch(viewName){
caseindex:
caseaboutus:
返回true;
}
返回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配置DTD 3.0 // EN
http://www.hibernate.org/dtd/hibernate-configuration -3.0.dtd>

< hibernate-configuration>

< session-factory>

<! - JDBC连接池(使用内置) - >
< property name =connection.pool_size> 12< / property>

<! - SQL方言 - >
< property name =dialect> org.hibernate.dialect.MySQLDialect< / property>

<! - 启用Hibernate的自动会话上下文管理 - >
< property name =current_session_context_class>线程< / property>

<! - 将所有执行的SQL回显到stdout - >
< property name =show_sql> true< / property>

<! - 启动时删除并重新创建数据库模式 - >
< property name =hbm2ddl.auto> update< / property>


< mapping class =com.myproject.model.MyTable/>
....


解决方案

使用自动装配无处不在或您的程序将无法正常工作。 Spring只能自动连接Spring应用程序上下文中的bean,这是您的 @Controller @Service @Repository 注释应该做。但是,如果您的配置XML中没有< context:component-scan base-package =your.base.package> 标记,则这些注释是无意义的。 >

因此,假设您的控制器,服务和DAO都位于包 com.repository 中的某个位置,则需要添加一行到你的XML配置。

 < context:component-scan base-package =com .repository/> 

这样做是告诉Spring在foo.bar.baz包中递归搜索(和所有子包含 @Controller @Service @Repository @Component ,实例化它们的单例实例,使他们有资格自动连接到其他类。



您还需要修改控制器和服务类以使用 @Autowired 。如果您使用新的关键字实例化了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;
}
返回null;
}

@RequestMapping(/ {viewName} / {viewName2})//郊区/ catname
public String index(@PathVariable(value =viewName)String viewName,Model model){
System.err.println(viewName);
if(isValidView(viewName)){
model.addAttribute(viewName,viewName);
返回页;
}
返回null;
}

private boolean isValidView(String viewName){
switch(viewName){
caseindex:
caseaboutus:
返回true;
}
返回false;
}
}

请注意,您将服务类自动连接到控制器中。



您的服务类需要实现一个界面。 Spring使用接口完成所有这些自动连线魔术。您不能自动连接不实现接口的类,除非您在XML配置中专门创建该类的实例。



您的服务类需要更改如下:

  @Service 
public class TestServiceImpl实现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实现TestRepDao {

@Autowired
private SessionFactory sessionFactory;

public void get(int id){
String hql =from Business where id =+ id;
查询查询= sessionFactory.getCurrentSession()。createQuery(hql);
}
}

实现界面TestRepDao:

  public interface TestRepDao {
public void get(int id);
}

您还可以删除


$的声明b $ b

 < bean id =TestRepclass =com.project.repository.TestRepImpl> 
< constructor-arg>
< ref bean =sessionFactory/>
< / constructor-arg>
< / bean>

从您的XML配置。



As你可以看到我已经改变了几个类名,以更好地适应Spring大会。您的应用程序应该从Controller到Service Class分层到DAO并再次退出。这应该可以让您按照我在这里提供的步骤。



需要记住的几件事:


  1. Spring讨厌新的关键字。如果你发现自己在使用它,你可能会做错事。

  2. 在整个应用程序中,Spring只需要使用组件扫描来选择任何一个类的一个实例。不要使用这些类来存储持久数据或状态。这条路径充满了线程问题,竞争条件和充满酸性蜘蛛的坑。

  3. 阅读并重新阅读文档,如果您从未使用过Spring,这些概念不容易之前。 Spring很容易使用,一旦了解它的工作原理,以及它如何使用它。

  4. Spring在接口上工作。如果你的类没有实现一个接口,Spring不能使用AspectJ加载时间编织(代理另一天的对话)来代替它,而不是刚开始使用的东西。如果您不知道Spring需要创建对象的代理,则需要重新阅读文档,直到您了解应用程序上下文。

  5. 我移动了 @Transactional 注释到Service类。这是因为DAO应该只关心从数据库访问和检索数据,而不必管理与数据库的连接/会话,这是服务类的工作。

  6. 我猜你在打了类似于

    这是Spring,告诉你它没有一个可以自动连接到任何类的TestService字段的bean。听说春天告诉你的事情,这样会给你带来很多麻烦。


  7. 不要气馁,当我试图学习如何使用春天,但我通过它,春天是我现在的第二个性质。


Question is not a duplicate as Hibernate is involved

As the James' answer partially solved the problem, I accepted it and opened a new question, please follow up here

I am trying to inject SessionFactory into a repository class; however, it looks like it does not work as the code returns NullPointer exception.I cleaned and rebuilt the project but the issue still exist. I also put @Autowired on the setSessionFactory method but did not help.

Interface

public interface TestRep {
public void get(int id);
}

Class

@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>

StackTrace

    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)

Jars

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;
    }

}

Test

@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" />
        ....
解决方案

You need to use Autowiring everywhere or your program won't work. Spring can only autowire beans that are present in the Spring application context, which is what your @Controller, @Service and @Repository annotations are supposed to do. However, these annotations are meaningless without a <context:component-scan base-package="your.base.package"> tag in your config XML.

So, assuming that your controller, service and DAO are all somewhere in the package com.repository, you need to add this line to your XML config.

<context:component-scan base-package="com.repository"/>

What this does is tells Spring to recursively search inside the foo.bar.baz package (and all sub-packages) for classes annotated with @Controller, @Service, @Repository and @Component, instantiate a singleton instance of them and make them eligible to be autowired into other classes.

You also need to modify your controller and service classes to use @Autowired. Spring can't manage your classes if you instantiate them with the new keyword. These beans are singletons (only one instance of them should ever exist in your program) for a reason.

Your controller needs to change as follows.

@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;
    }
}

Notice that you Autowire your service class into your controller.

Your service class needs to implement an interface. Spring does all this autowiring magic using interfaces. You cannot autowire a class that does not implement an interface, unless you specifically create an instance of that class in your XML config.

Your service class needs to change as follows:

@Service 
public class TestServiceImpl implements TestService {
    @Autowired
    private TestRepDao testDao;

    @Transactional
    public void get(int i){
         testDao.get(i);
    }
}

and create an interface called TestService.

public interface TestService{
    public void get(int i);
}

and then your DAO becomes

@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);
    }
}

which implements the interface TestRepDao:

public interface TestRepDao{
    public void get(int id);
}

you can also remove the declaration of

<bean id="TestRep" class="com.project.repository.TestRepImpl">
    <constructor-arg>
        <ref bean="sessionFactory" />
    </constructor-arg>
</bean>

from your XML configuration.

As you can see I've changed a few class names to better fit with the Spring convention. Your application is supposed to layer down from Controller to Service Class to DAO and back out again. This should work providing you follow the steps I've laid out here.

A few things to keep in mind:

  1. Spring hates the new keyword. If you find yourself using it, you are probably doing something wrong.
  2. There is only ever one instance of any of your classes that Spring picks up with the component scan in your entire application. DO NOT use these classes to store persistent data or states. That path is full of threading issues, race conditions and pits full of acid spiders.
  3. Read and re-read the documentation, these are not easy concepts to pick up if you have never used Spring before. Spring is super easy to use, once you understand how it works, and how it expects you to use it.
  4. Spring works on interfaces. If your class doesn't implement an interface, Spring can't proxy it without using AspectJ Load Time Weaving, which is a conversation for another day, and not something you should be using, just starting out. If you don't know why Spring needs to create a proxy of your object, you need to re-read the documentation until you understand the application context.
  5. I moved the @Transactional annotation into the Service class. This is because the DAO should only be concerned with accessing and retrieving the data from the database, NOT having to manage the connection/session to the database, that is the job of the service class.
  6. I'm guessing you started using the new keyword after hitting exceptions saying something similar to

    This is Spring telling you that it doesn't have a bean that can be autowired into the TestService field on whatever class. Listen when Spring is telling you things, it will save you a lot of bother.

  7. Don't be discouraged, I faced all these problems when I was trying to learn how to use Spring, but I got through it and Spring is second nature to me now.

这篇关于Spring 4.1.5.RELEASE没有为Hibernate 4.3.8.Final的SessionFactory执行依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 11:58