简体   繁体   English

Spring 3在自定义bean中接收servletContext

[英]Spring 3 receive servletContext in custom bean

my problem is that I can't get servletcontext in my bean. 我的问题是我无法在我的bean中获取servletcontext。 I created custom bean "FileRepository" and I need to get ServletContext there. 我创建了自定义bean“FileRepository”,我需要在那里获取ServletContext。 here is the code 这是代码

package com.pc.webstore.utils;

import java.io.File;
import java.nio.file.Files;

import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.ServletContextAware;
public class FileRepository implements ServletContextAware {

private ServletContext servletContext;

public String saveFile(File file){
    File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            ...
}

@Override
public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;
    }
}

registration in ApplicationContext.xml 在ApplicationContext.xml中注册

 <bean id="fileStorage" class="com.pc.webstore.utils.FileRepository"/>

when saveFile(File file) starts, I recive Nullpointerexception because servletContext == null. 当saveFile(文件文件)启动时,我重新发现Nullpointerexception,因为servletContext == null。

So why servletcontext does not injected? 那么为什么servletcontext没有注入呢? I have ContextLoaderListener registred in web.xml 我在web.xml中注册了ContextLoaderListener

   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

I found that there is some scopes. 我发现有一些范围。 May be problem is there. 可能是问题在那里。 Tell me briefly about applicationsontext scope or give the link pleas. 请简要介绍一下applicationontext范围或给出链接请求。 Thanks for help. 感谢帮助。 I spent a lot of time for this problem. 我花了很多时间来解决这个问题。

After some debuging I understood that setServletContexr method of servletcontextaware is actually was called when app starts but when I tried to store file with FileRepository from my controller, it was already anather object with null servletContext field. 经过一些调试后,我明白servletcontextaware的setServletContexr方法实际上是在应用程序启动时调用的,但是当我尝试使用FileRepository从我的控制器存储文件时,它已经是具有null servletContext字段的anather对象。

Is there a way just to autowier servlet context in my custom bean when i want, like in controller? 有什么办法可以在我想要的时候在我的自定义bean中自动加载servlet上下文,比如在控制器中吗?

Finaly I get servletContext via ServletContextAware. 最后我通过ServletContextAware获取servletContext。 I change the way of creation fileRepository bean. 我改变了创建fileRepository bean的方式。 From this 由此

public String create(@Valid Item item, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, FileRepository fileRepository)     {

to this 对此

@Autowired
private FileRepository fileRepository;

@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(@Valid Item item, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {

ContextLoaderListener loads an ApplicationContext that becomes the global parent context for the application. ContextLoaderListener加载一个ApplicationContext,它成为应用程序的全局父上下文。 There is no ServletContext there. 那里没有ServletContext。 ServletContext only exists within (pardon the overloading of terms) the CONTEXT of a SERVLET- for instance, the DispatcherServlet. ServletContext仅存在于(请原谅术语的重载)SERVLET的CONTEXT中,例如DispatcherServlet。 Every DispatcherServlet (typically you'd only have one) registers a child context that points back to the global parent context registered by the ContextLoaderListener. 每个DispatcherServlet(通常只有一个)都会注册一个子上下文,该上下文指向ContextLoaderListener注册的全局父上下文。 ApplicationContexts are like classloaders. ApplicationContexts就像类加载器一样。 When the IOC container goes "looking" for a bean, each ApplicationContext can look "up" to its parent to try to find it, but it can't look down. 当IOC容器“查找”bean时,每个ApplicationContext都可以向上查看其父级以尝试查找它,但它不能向下看。 Children can also override bean definitions from their parent context. 孩子们也可以从父上下文中覆盖bean定义。

Now... it would seem your problem is that your bean is defined in global parent context where there is no ServletContext to be found. 现在......看起来你的问题是你的bean是在没有找到ServletContext的全局父上下文中定义的。 (It can't look "down" to its children to find it.) (它不能让它的孩子“向下”找到它。)

What you need to do is move the fileStorage bean definition "down" into the ApplicationContext for the DispatcherServlet. 您需要做的是将fileStorage bean定义“down”移动到DispatcherServlet的ApplicationContext中。

When you define a DispatcherServlet in your web.xml, you usually specify where it can find the files that define its child context. 在web.xml中定义DispatcherServlet时,通常会指定在何处可以找到定义其子上下文的文件。 Like so: 像这样:

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:/web-context/*.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Move that bean definition down into the location specified by contextConfigLocation and everything should work as you expect. 将该bean定义向下移动到contextConfigLocation指定的位置,一切都应该按预期工作。

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

相关问题 如何在Spring XML元数据配置中为bean设置ServletContext属性 - How to set ServletContext property for a bean in Spring XML metadata configuration Spring servletcontext无法在根应用程序上下文中访问bean - Spring servletcontext cannot access bean in root application context Spring Custom Converter-转换为Bean或不转换为Bean - Spring Custom Converter - To Bean or Not to Bean 将Filter bean添加到ServletContext - Add Filter bean to ServletContext 使用 ServletContext 加载 Applicationscoped Bean - Load Applicationscoped Bean with ServletContext 自定义Spring Bean参数 - Custom Spring Bean Parameters 如何作为春豆接受非英语字符 - how to receive nonenglish character as spring bean Java 在 ServletContext 资源 [/WEB-INF/spring-servlet.xml] 中定义名为“dataSource”的无效 bean 定义: - Java Invalid bean definition with name 'dataSource' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Spring Tiles Application:使用ServletContext资源中定义的名称viewResolver创建bean时出错 - Spring Tiles Application:Error creating bean with name viewResolver defined in ServletContext resource 将Spring Security和JSF 2结合在一起:在ServletContext资源中创建名称为&#39;dataSource&#39;的bean时出错 - Combining Spring security and JSF 2 : Error creating bean with name 'dataSource' defined in ServletContext resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM