且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

修复Spring MVC应用程序中的Null EntityManger?

更新时间:2023-01-09 23:07:24

今天我很幸运能够和一位顾问讨论这个问题,他能够帮我整理一切。

I was lucky enough today to be able to speak with a consultant about this issue, he was able to help me sort the whole thing out.

所以我的问题是Spring MVC正在建立两个不同的上下文,一个应用程序上下文,在applicationContext.xml中定义,一个web上下文,在dispatcher-servlet.xml中定义。

So my problem is that Spring MVC was establishing two distinct contexts, one application context, defined in applicationContext.xml and one web context, defined in dispatcher-servlet.xml.

来自一个上下文的Bean无法与另一个上下文中的bean通信,因此当我在applicationContext.xml中启动我的持久化上下文时,我无法在由dispatcher-servlet加载的bean中访问它.xml,即我的控制器。

Beans from one context can not talk to beans in another context, thus when I initilized my persistence context inside of applicationContext.xml, I could not access it in beans loaded by dispatcher-servlet.xml, ie my controllers.

当Netbeans自动生成我的Spring MVC的基础时,它默认设置它。在一些大型Web应用程序中,将应用程序的Web部分与其他逻辑(持久性,业务代码等)区分开来是有意义的。在我的情况下,我试图将我的实体管理器直接自动注入我的控制器,这对我不利。

When Netbeans auto-generated the base to my Spring MVC it set this up by default. In some large web applications, it would make sense to separate the web part of the application in a context distinct from the rest of the logic (persistence, business code, etc). In my case, where I am trying to auto inject my entity manager directly into my controllers, this worked against me.

要解决这个问题我移动了行

To fix the issue I moved the line

<import resource="classpath:META-INF/persistence-context.xml"/>

从applicationContext.xml到我的dispatcher-servlet.xml。然后我的控制器从@PersistanceContext注释中正确地注入了EntityManagers。

From the applicationContext.xml, to my dispatcher-servlet.xml. My controllers then were properly injected with EntityManagers from the @PersistanceContext annotation.