Spring 3 get servletContext in custom bean

my problem is that I cannot get the servletcontext in my bean. I created a custom bean "FileRepository" and I need to get the 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

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

when saveFile (file) starts, I get a Nullpointerexception because servletContext == null.

So why is servletcontext not being introduced? I have a ContextLoaderListener registered in web.xml

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

I found that there are some areas. Maybe there is a problem. Tell me briefly about the scope of applicationontext or pass links. Thanks for the help. I spent a lot of time on this problem.

, setServletContexr servletcontextaware , FileRepository , anather servletContext.

autowier bean, , , ?

, servletContext ServletContextAware. fileRepository bean.

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

@Autowired
private FileRepository fileRepository;

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

ContextLoaderListener ApplicationContext, . ServletContext. ServletContext (pardon overloading terms) CONTEXT SERVLET, DispatcherServlet. DispatcherServlet ( ) , , ContextLoaderListener. ApplicationContexts . IOC "" bean, ApplicationContext "" , , . bean .

... , , bean , ServletContext. ( "" , .)

, fileStorage bean "" ApplicationContext DispatcherServlet.

DispatcherServlet web.xml, , , . :

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

bean , contextConfigLocation, , .

+4

All Articles