結論
@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