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

Java 如何在@Configuration或@SpringBootApplication类中访问ServletContext,java,spring,spring-boot,autowired,postconstruct,Java,Spring,Spring Boot,Autowired,Postconstruct,我正在尝试更新一个旧的Spring应用程序。具体地说,我正试图将所有bean从旧的xml定义的表单中拉出来,并将它们拉到@SpringBootApplication格式中(同时大幅减少定义的bean的总数,因为其中许多不需要是bean)。我目前的问题是,我不知道如何使ServletContext对需要它的bean可用 我当前的代码如下所示: package thing; import stuff @SpringBootApplication public class MyApp {

我正在尝试更新一个旧的Spring应用程序。具体地说,我正试图将所有bean从旧的xml定义的表单中拉出来,并将它们拉到@SpringBootApplication格式中(同时大幅减少定义的bean的总数,因为其中许多不需要是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
    }
}
我得到的错误是:
thing.MyApp中的字段servletContext需要找不到类型为“javax.servlet.servletContext”的bean。


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

请注意访问
servlet上下文的最佳实践:您不应该在主应用程序类中执行此操作,但是e。G控制器

否则,请尝试以下操作:

实现
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;
    }


}

所以我目前在Intellij IDEA工作,它抱怨如果我试图实现ServletContextAware而没有实现抽象方法setServletContext(ServletContext)。我可能会利用这一点,我会尝试一下,但是你能在回答中以这种或那种方式解决这个问题吗?是的,如果你实现了这个接口,你需要添加
setServletContext
方法。更新了我的答案。酷。看起来很有效。事实证明,我成功地在setServletContext本身下适应了逻辑,并且能够完全摆脱populateContext()和@PostConstruct。目前已被接受,并且将继续被接受,只要它在以后的过程中不会产生其他错误。所以。。。我设法达到了它实际编译和运行的程度。。。出于我不理解的原因,setServletContext从未被调用过。您对此有任何了解吗?setServletContext也不适用于我,它不适用于Spring Boot Starter 2.2.5