0
1

More than 3 years have passed since last update.

【Spring Boot】CORSをアプリケーション全体で設定する時にEnvironmentインタフェースを使いたい

Posted at

概要

Spring MVC で CORS 設定の記事で解説されている通り、Spring BootでCORSの設定をする際にはアノテーションを個別に設定する方法と、アプリケーション全体で設定する方法があります。個別のパスでCORSの設定をするケースは、個人的にはあまり多くないかなと思っていてまずは、アプリケーション全体で設定を選択すると思います。今回は、アプリケーション全体で設定する時の課題に関して書いてみます。

課題

上記の記事で紹介されているWebMvcConfigのclassを定義する方法では、Environmentインタフェースを使用できません。理由として考えられるのは@Configurationのアノテーションが付与されているclassは、applicantion.propertiesと同列の扱いとなり、このclass内ではEnvironmentインタフェースの設定が読み込めないと考えられます。Spring Bootがプロパティファイルを読み込む方法に一同驚愕!!の記事が参考になります。

どうすれば良いのか

とはいえ、やはり環境毎にCORSの許可URLを変えたいので、どうすれば良いのかというのがSpring Boot enabling CORS by application.propertiesで紹介されています。いくつか方法はあるのですが、SpringBootApplicationに直接WebMvcConfigの定義を書いてしまう方法が、シンプルで分かりやすいかなと感じました。ので、以下にサンプルの実装をのせておきます。

サンプル実装

SampleApplication.java

@SpringBootApplication
public class SampleApplication {

    @Autowired
    private Environment env;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                String url = env.getProperty("allowed.url");
                registry.addMapping("/**")
                        .allowedOrigins(url)
                        .allowCredentials(true);
            }
        };
    }

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

}

0
1
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
0
1