简体   繁体   English

将Spring上下文注入非Spring类

[英]Injecting Spring Context into Non-spring Class

I'm relatively new to Java and coming from a web background I found myself trying to implement a web application in Spring. 我是Java的新手,来自Web背景,我发现自己试图在Spring中实现Web应用程序。

The main problem is I have the following folder structure: 主要问题是我具有以下文件夹结构: 在此处输入图片说明

And I am trying to inject Spring context into any class found in the Controllers folder, which basically, as far as I understood means that my classes are not Spring-dependant. 而且我正在尝试将Spring上下文注入到Controllers文件夹中找到的任何类中,据我所知,基本上这意味着我的类与Spring无关。

The application uses MongoDB as a backend, and I am trying to instantinate the context like this: 该应用程序使用MongoDB作为后端,而我试图实例化这样的上下文:

WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();

IODataInterface mongo = context.getBean(BookModel.class);

I'm getting this exception on the context.getBean(...) line: com.web.spring.Controllers.DemoController.DemoController(DemoController.java:19) 我在context.getBean(...)行上收到此异常:com.web.spring.Controllers.DemoController.DemoController(DemoController.java:19)

Any help is appreciated and I'd be really glad if someone could properly explain me the actual terminology as, you might have guessed already, I have jumped into some pretty advanced stuff for someone with 0 Java work experience. 感谢您的帮助,如果有人可以正确地解释我的实际术语,我将非常高兴,因为您可能已经猜到了,对于那些具有0 Java工作经验的人,我已经跳入了一些相当高级的文章。

Full exception stack: 完整的异常堆栈:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

And as far as I see, the context seems to get created, but the getBean() doesn't work. 据我所知,上下文似乎已创建,但是getBean()不起作用。 I'm really confused now. 我现在真的很困惑。

You seem to be trying to get an instance of a model class (annotated by @Document I imagine, since you're using MongoDb). 您似乎正在尝试获取模型类的实例(我想象中的@Document带有注释,因为您正在使用MongoDb)。 @Document and JPA @Entity annotated classes are actually not Spring Beans. @Document和JPA @Entity注释的类实际上不是Spring Bean。

So to instantiate a new one you can just use new BookModel() . 因此,要实例化一个新实例,您可以使用new BookModel()

PS. PS。 as an aside, please adopt a low case package/folder naming convention. 顺便说一句,请采用小写的包/文件夹命名约定。 Only class names should start with a capital letter. 仅班级名称应以大写字母开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM