在启动时填充spring servlet上下文

时间:2013-03-02 02:16:59

标签: spring servlets

这可能是一个重复的问题。

我的问题是:我想从属性文件中读取一个属性,并在启动应用程序后立即将其放入servlet上下文中。

有人可以帮我吗?

提前致谢。

1 个答案:

答案 0 :(得分:4)

实现Spring的ApplicationListener:

@Component
public class MyApplicationListener implements ApplicationListener  {

  /* if you want to set predefined properties you even don't have to load properties filed - you can directly inject properties values ... you can configure it in applicationContext.xml
   <util:list id="locations">
      <value>classpath:appconfig1.properties</value>
      <value>classpath:appconfig2.properties</value>
   </util:list>
   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
              p:locations-ref="locations" />
  */         

  @Value("${myproperty1}") private String myProperty1;
  @Value("${myproperty2}") private String myProperty2;
  @Value("${myproperty3}") private String myProperty3;

  public void onApplicationEvent(ApplicationEvent event) {

    if (event instanceof ContextClosedEvent) {
        applicationClosed();
        return;
    }

    if (!(event instanceof ContextRefreshedEvent)) return;
    ContextRefreshedEvent e = (ContextRefreshedEvent) event;
    ApplicationContext appContext = e.getApplicationContext();
    if (!(appContext instanceof WebApplicationContext)) return;
    WebApplicationContext ctx = (WebApplicationContext) e.getApplicationContext();
    ServletContext context = ctx.getServletContext();


    context.setAttribute("myProperty1", myProperty1);
    context.setAttribute("myProperty2", myProperty2);
    context.setAttribute("myProperty3", myProperty3);

  }
}