Fixing Null EntityManger in Spring MVC application?

后端 未结 4 1773
逝去的感伤
逝去的感伤 2020-12-09 06:49

In the following code I am trouble with my injected EnitityManager, which always shows up as null;

public class GenericController extends Ab         


        
4条回答
  •  死守一世寂寞
    2020-12-09 07:19

    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.

    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.

    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.

    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

    
    

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

提交回复
热议问题