我必须将带有servlet的旧Spring应用程序移植到spring boot应用程序。
我已为现有servlet配置了java样式配置文件,但我无法将spring环境传递给它们。
例如java config看起来像这样(我跳过了真实的映射)
@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环境以从application-X.properties获取数据,具体取决于给定的spring配置文件。
答案 0 :(得分:0)
Spring只能注入Spring bean,你需要在InitServlet
配置类中注册ServletConfig
作为Bean。