1
2

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 3 years have passed since last update.

@PropertySourceをapplication.propertiesに使ってはいけない

Posted at

結論

@PropertySource(name = "application", value = "classpath:application.properties")

みたいに@PropertySourceを使ってapplication.propertiesを読み込むと、Spring BootのExternalize Configurationの仕組みが働かないので、やるべきではありません。
@PropertySourceの使いどころは、application.properties以外、かつ、環境依存しないプロパティファイルの読み込みに使うものと思います。

やってみる

ソースとプロパティファイル

application.properties
key1 = value1
key2 = value2
TestConfig.java
package com.example.demo;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;

@Configuration
@PropertySource(name = "application", value = "classpath:application.properties")
public class TestConfig {
	@Resource
	ConfigurableEnvironment environment;
	
    @Bean
    public PropertiesPropertySource propertySource() {
        return (PropertiesPropertySource) environment.getPropertySources().get("application");
    }
}

key1は@PropertySourceで、key2は@Valueで読むようにしました。

TestRunner.java
package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;

@Component
public class TestRunner implements ApplicationRunner {

	@Autowired
	PropertiesPropertySource propertySource;
	
	@Value("${key2}")
	String key2;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("key1 = " + propertySource.getProperty("key1"));
		System.out.println("key2 = " + key2);
	}

}

引数なしで実行

key1 = value1
key2 = value2

application.propertiesの設定の通り出力されます。

引数を付けて実行

引数:--key1=value11 --key2=value22

key1 = value1
key2 = value22

key2は正しく引数の指定で上書きされていますが、key1は引数の指定を無視してそのままです。

動作環境

OpenJDK11.0.2
Spring Boot 2.3.2

参考

Spring Boot Features - 2. Externalized Configuration

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?