2
プロパティファイルではなくデータベースからプロパティをロードし、プロセスが完了するまでメモリに保持する必要があるバッチアプリケーションを作成しようとしています。Springアプリケーションでプロパティファイルの代わりにデータベースからプロパティをロードする方法
プロパティファイルではなくデータベースからプロパティをロードし、プロセスが完了するまでメモリに保持する必要があるバッチアプリケーションを作成しようとしています。Springアプリケーションでプロパティファイルの代わりにデータベースからプロパティをロードする方法
ConfigurableEnvironment
コンポーネントを使用して、既存の環境にカスタムプロパティを追加できます。
ContextRefreshedEvent
をリッスンしてアプリケーションを完全に初期化すると、通常、データベースから何かを取得して環境とマージすることができます。
しかし、あなたはそれを自分のライフサイクルに束縛することができます。
ここは簡単な例です。
@Component
public static class PropertyEnvironment implements ApplicationListener<ContextRefreshedEvent> {
private final ConfigurableEnvironment configurableEnvironment;
private final DatabasePropertyRepository propertiesRepository;
@Autowired
public PropertyEnvironment(ConfigurableEnvironment configurableEnvironment,
DatabasePropertyRepository propertiesRepository) {
this.configurableEnvironment = configurableEnvironment;
this.propertiesRepository = propertiesRepository;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
final Map<String, Object> properties = propertiesRepository.findAll().stream()
.collect(Collectors.toMap(DatabaseProperty::getName, DatabaseProperty::getValue));
configurableEnvironment.getPropertySources().addLast(new MapPropertySource("db", properties));
}
}
I:
interface DatabasePropertyRepository extends JpaRepository<So44850695Application.DatabaseProperty, String> {}
これは、既存の環境でそれをマージする方法である:リポジトリ/ DAOで
@Entity
@Table(name = "database_properties")
public static class DatabaseProperty extends AbstractPersistable<String> {
private String name;
private String value;
public DatabaseProperty() {}
public DatabaseProperty(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() { return name; }
public String getValue() { return value; }
}
:
が、これは、データベースのプロパティ定義であると言いますこれが最も簡単な方法だと考えてください。