0

重複した質問かもしれません。

私の質問は、プロパティ ファイルからプロパティを読み取り、アプリケーションを起動したらすぐにそれをサーブレット コンテキストに入れたいということです。

誰でもそれについて私を助けてもらえますか?

前もって感謝します。

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 に答える