0

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

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

有人可以帮我吗?

提前致谢。

4

1 回答 1

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);

  }
}
于 2013-03-02T20:14:34.213 回答