一尘不染

如何在@Configuration或@SpringBootApplication类内部访问ServletContext

spring-boot

我正在尝试更新旧的Spring应用程序。具体来说,我正在尝试将所有bean从旧的xml定义的表单中拉出,并将它们拉成@SpringBootApplication格式(同时大幅减少了已定义的bean的总数,因为其中许多不需要豆子)。我当前的问题是我无法弄清楚如何使ServletContext可用于需要它的bean。

我当前的代码如下所示:

package thing;

import stuff

@SpringBootApplication
public class MyApp {

    private BeanThing beanThing = null;

    @Autowired
    private ServletContext servletContext;

    public MyApp() {
        // Lots of stuff goes here.
        // no reference to servletContext, though
        // beanThing gets initialized, and mostly populated.
    }

    @Bean public BeanThing getBeanThing() { return beanThing; }

    @PostConstruct
    public void populateContext() {
        // all references to servletContext go here, including the
        // bit where we call the appropriate setters in beanThing
    }
}

我得到的错误: Field servletContext in thing.MyApp required a bean of type 'javax.servlet.ServletContext' that could not be found.

所以…我想念什么?我应该添加到路径中吗?我需要实现一些接口吗?我不能自己提供Bean,因为重点是我试图访问自己没有的servlet上下文信息(getContextPath()和getRealPath()字符串)。


阅读 457

收藏
2020-05-30

共1个答案

一尘不染

请注意访问的最佳实践ServletContext:您不应在主应用程序类中进行操作,而应在例如控制器中进行操作。

否则,请尝试以下操作:

实现ServletContextAware接口,Spring会为您注入。

删除@Autowired该变量。

添加setServletContext方法。

@SpringBootApplication
public class MyApp implements ServletContextAware {

    private BeanThing beanThing = null;

    private ServletContext servletContext;

    public MyApp() {
        // Lots of stuff goes here.
        // no reference to servletContext, though
        // beanThing gets initialized, and mostly populated.
    }

    @Bean public BeanThing getBeanThing() { return beanThing; }

    @PostConstruct
    public void populateContext() {
        // all references to servletContext go here, including the
        // bit where we call the appropriate setters in beanThing
    }

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


}
2020-05-30