【问题标题】:Access spring environment in a separate servlet在单独的 servlet 中访问 spring 环境
【发布时间】:2017-07-31 12:50:25
【问题描述】:

我必须将带有 servlet 的旧 Spring 应用程序移植到 Spring Boot 应用程序。

我已经为现有的 servlet 配置了一个 java 风格的配置文件,但是我无法将 spring 环境传递给它们。

例如 java 配置看起来像这样(我已经跳过了真正的映射)

@Configuration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean initServletRegistration() throws ServletException {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        try {
            bean.setServlet(new InitServlet());
        } catch (Exception e) {
            NewLog.logError(this, "InitServlet threw an exception: " + e, e);
            throw new ServletException("InitServlet threw an exception: " + e);
        }
        bean.setUrlMappings(Arrays.asList("...."));
        bean.setLoadOnStartup(1);
        return bean;
    }

    @Bean
    public ServletRegistrationBean testReceiveServiceServletRegistration() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new TestReceiveServiceServlet());
        bean.setUrlMappings(Arrays.asList("...."));
        return bean;
    }

    @Bean
    public ServletRegistrationBean insertIntoInputQueueServletRegistration() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new InsertIntoInputQueueServlet());
        bean.setUrlMappings(Arrays.asList("...."));
        return bean;
    }

    @Bean
    public ServletRegistrationBean nonCxfRedirectServletRegistration() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new NonCxfRedirectServlet());
        bean.setUrlMappings(Arrays.asList(".....");
        return bean;
    }

然后在 servlet 中,我想注入 spring 环境,但对于 env vairable,我总是得到 null

public class InitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Autowired
    Environment env;

    public InitServlet() throws Exception {
    }
........
}

servlet 本身工作正常如果我在它们响应的给定 url 映射上调试它们,我只想从它们访问 spring 环境,以根据给定的 spring 配置文件从 application-X.properties 获取数据。

【问题讨论】:

  • 将它们注册为@Bean,并且不要在产生ServletRegistrationBean的方法中构造它们。

标签: spring servlets autowired


【解决方案1】:

Spring只能注入Spring bean,需要在ServletConfig配置类中注册InitServlet为Bean。

【讨论】:

    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2021-10-08
    • 2021-04-26
    相关资源
    最近更新 更多