Aqueduct入門四步走(三)配置和自測
曾經有位大佬說過,java之所以能縱橫江湖幾十年,完全是因爲Spring太牛逼了。而Aqueduct就是Dart界的SpringBoot。
目錄
程序配置
之前我們已經玩過數據庫連接了。但是存在一點問題,我們是把數據庫連接配置硬編碼到了prepare()
,這非常不安全。而在Springboot中,我們都是把這些配置放在.yaml
或.property
文件中。那麼Aqueduct能不能這樣玩?
打開config.yaml添加內容如下:
database:
host: localhost
port: 5432
username: heroes_user
password: password
databaseName: heroes
yaml是以縮緊來表示歸屬的,所以縮進不能省略。
然後在lib/channel.dart下面添加一個新的類型:
class HeroConfig extends Configuration {
HeroConfig(String path): super.fromFile(File(path));
DatabaseConfiguration database;
}
繼承自Configuration表示這是一個配置類,目前只有一個屬性database
,它對應着config.yaml中的database
屬性。如果兩邊的屬性對應不上,是會報錯的。
除了數據庫配置,我們還可以在這裏配置host port username password 等等。
接下來我們還是從prepare()
方法去加載配置文件:
@override
Future prepare() async {
logger.onRecord.listen(
(rec) => print("$rec ${rec.error ?? ""} ${rec.stackTrace ?? ""}"));
final config = HeroConfig(options.configurationFilePath);
final dataModel = ManagedDataModel.fromCurrentMirrorSystem();
final persistentStore = PostgreSQLPersistentStore.fromConnectionInfo(
config.database.username,
config.database.password,
config.database.host,
config.database.port,
config.database.databaseName);
context = ManagedContext(dataModel, persistentStore);
}
這裏重點就一句代碼final config = HeroConfig(options.configurationFilePath);
。