Spring Boot で外部設定ファイルを読み込む方法
スプリングブートでは、@PropertySourceアノテーションを使用することで外部設定ファイルを読み込むことができます。これを実行する一般的な方法は次のとおりです。
- ApplicationConfigなどの設定クラスを作成します。
@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
@Autowired
private Environment env;
// 定义需要读取的配置项
@Value("${my.property}")
private String myProperty;
// 其他配置项...
// 提供获取配置项的方法
public String getMyProperty() {
return myProperty;
}
// 其他获取配置项的方法...
}
- application.propertiesファイルに設定を定義する。例:
my.property=value
- Spring Bootアプリケーションのエントリクラスでは、@ComponentScanアノテーションでコンフィグクラスをスキャンし、@Autowiredでコンフィグクラス内の設定項目をインジェクションする
@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class Application {
@Autowired
private ApplicationConfig applicationConfig;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
public void init() {
// 使用配置项
String myProperty = applicationConfig.getMyProperty();
// 其他使用配置项的逻辑...
}
}
これらの手順に従うと、Spring Boot アプリケーションで外部構成ファイルの構成アイテムを読み取ることができます。