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