3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ServletContextListenerにてSpringのBeanなどリソースを取得する方法

Last updated at Posted at 2016-03-03

こんなServletContextListenerがありまして:

@Override
public void contextInitialized(ServletContextEvent event) {
    String mode = "Springプロパティファイルに定義された定数";
    if ("xx".equals(mode)) {
        // ある業務処理
    }

}

contextInitializedにSpringプロパティファイルに定義されたものがある条件を満たす場合のみ、「ある業務処理」が実行されます。

もちろん、web.xmlにも<init-param>が使えますが、できるだけSpringの資産を流用したいので、web.xmlを修正しない方針です。

したがって、contextInitializedにてSpringのContextを取得するとなりました。

修正後、メソッドの中身はこうなります:

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
Environment env = context.getBean(Environment.class);
String mode = env.getProperty("some-prop");

if ("xx".equals(mode)) {
    // ある業務処理
}

注意: ちなみに、web.xmlにてServletContextListenerの位置はorg.springframework.web.context.ContextLoaderListenerの後ろにしなければなりません。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?