java - 如何访问 @Configuration 或 @SpringBootApplication 类中的 ServletContext

标签 java spring spring-boot autowired postconstruct

我正在尝试更新旧的 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
    }
}

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

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

最佳答案

请注意访问 ServletContext 的最佳实践:您不应该在主应用程序类中执行此操作,但 e. G。一个 Controller 。

否则请尝试以下操作:

实现 ServletContextAware 接口(interface),Spring 将为您注入(inject)它。

删除变量的@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;
    }


}

关于java - 如何访问 @Configuration 或 @SpringBootApplication 类中的 ServletContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50047521/

相关文章:

Spring @RequestParam 映射 boolean 基于 1 或 0 而不是 true 或 false

java - 是否可以在少数线程但不是所有线程之间共享变量?

unit-testing - 使用 Spring Boot 进行身份验证过滤器的集成测试

java - VLCJ - 在 64 位 Linux 上捆绑 native VLC 库

java - 从 log4j 转换后的 Logback 模式异常

java - Java中的缩略图程序每次刷新页面时都会给出图像的随机图像

spring - 如何使用 Spring REST 模板设置每个请求的超时?

java - Mule ConsumerIterator 中缺少记录

java - 运行我的应用程序的 EntityManager 没有持久性提供程序

java - Vaadin 网格不会在事件中刷新