如何在 @Configuration 或 @SpringBootApplication 类中访问 ServletContext

Ben*_*den 4 java spring autowired postconstruct spring-boot

我正在尝试更新旧的 Spring 应用程序。具体来说,我试图从旧的 xml 定义形式中提取所有 bean 并将它们拉入 @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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Ben*_*ams 6

请注意访问 的最佳实践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;
    }


}
Run Code Online (Sandbox Code Playgroud)

  • 所以...我设法达到了它实际编译和运行的程度...并且由于我不明白的原因,setServletContext 从未被调用。你对此有了解吗? (2认同)
  • setServletContext 也没有为我调用,在 Spring Boot Starter 2.2.5 中不起作用 (2认同)