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);
。