java - 如何访问 @Configuration 或 @SpringBootApplication 类中的 ServletContext
问题描述
我正在尝试更新旧的 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() 字符串)。
解决方案
请注意访问的最佳实践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;
}
}
推荐阅读
- python - 我可以在 python 脚本中强制字符编码吗?
- javascript - 模块化 javascript 代码 SONAR 重复块
- docker - 如何加快 Gitlab 构建过程 - Docker & Yarn/Lerna
- c++ - C++ double 变量在复制到另一个 double 中时会丢失精度
- javascript - 如何计算“li”元素并使用 Selenium 和 JavaScript 断言它们的数量?
- ios - 应用程序终止时用户未注销
- java - 如何检查当前登录的用户属性是否与android中的另一个表属性相等?
- r - R将函数应用于多个数据帧
- swift - 推送视图控制器时发现线程错误为零
- java - 不满足条件异常;必须被抓住或宣布被扔掉