在启动期间访问servlet中的Spring占位符

时间:2014-12-03 11:04:42

标签: java spring servlets configuration

在Spring框架基础应用程序(使用struts而不是SpringMVC)中,我们希望在Web应用程序启动期间在servlet中读取弹簧占位符并将其置于应用程序范围内。

我发现我无法在实现@Value的{​​{1}}中使用servlet

这似乎是正确的,因为Spring不知道ServletContextListener启动。我使用下面的代码

servlet

我不是一个春天的人,所以如果有更好的方法,请告诉我。 此外,是否有更好的方式来访问@WebListener public class StartUp implements ServletContextListener { private static final Logger LOG = LoggerFactory .getLogger(StartUp.class); @Override public void contextInitialized(ServletContextEvent event) { //As the servlet starts outside spring application context The @Value can not //be used to inject values //The Spring beanFactory class can be used to get values from property files. //This is same as using @value. ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(event.getServletContext()); ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext) .getBeanFactory(); String template = beanFactory.resolveEmbeddedValue("${site.active.template}"); event.getServletContext().setAttribute("TEMPLATE", template ); LOG.debug("Current template is : {}",template ); } @Override public void contextDestroyed(ServletContextEvent sce) { LOG.debug("Webapplcaition destroyed"); } }

1 个答案:

答案 0 :(得分:0)

简单搜索显示struts的插件用于此目的:

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
        <set-property property="contextConfigLocation"
            value="/WEB-INF/context.xml" />
    </plug-in>