Can't Autowire ServletContext

后端 未结 3 1516
夕颜
夕颜 2020-12-20 11:50

I\'m new with Spring, and I\'m trying to use the @Autowire annotation for the ServletContext with my class attribute:

@Controller
public class ServicesImpl i         


        
相关标签:
3条回答
  • 2020-12-20 12:28

    You'll probably want to take a look at MockServletContext which can be used in unit tests.

    0 讨论(0)
  • 2020-12-20 12:37

    Implement the ServletContextAware interface and Spring will inject it for you

    @Controller
    public class ServicesImpl implements Services, ServletContextAware{
    
    
    private ServletContext context;
    
    public void setServletContext(ServletContext servletContext) {
         this.context = servletContext;
    }
    
    0 讨论(0)
  • 2020-12-20 12:40

    ServletContext is not a Spring bean and it can, therefore, not be injected unless you implement ServletContextAware.

    If one thinks in modules or layers then the servlet context shouldn't be available outside the web module/layer. I suppose your ServicesImpl forms part of the business or service layer.

    If you gave a little more context we might be able to suggest better alternatives.

    0 讨论(0)
提交回复
热议问题