我尝试将示例代码迁移到Kotlin,在原始Java版本中,有一个CommandLineRunner
用于初始化一些数据。
@Component
@Slf4j
class DataInitializer implements CommandLineRunner {
private final PostRepository posts;
public DataInitializer(PostRepository posts) {
this.posts = posts;
}
@Override
public void run(String[] args) {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.just("Post one", "Post two")
.flatMap(
title -> this.posts.save(Post.builder().title(title).content("content of " + title).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
}
在Kotlin版本中,我尝试在Kotlin BeanDefinitionDSL中定义一个CommandLineRunner
bean,
bean {
CommandLineRunner {
println("start data initialization...")
val posts = ref<PostRepository>();
Flux.concat(
posts.deleteAll(),
posts.saveAll(
arrayListOf(
Post(null, "my first post", "content of my first post"),
Post(null, "my second post", "content of my second post")
)
)
)
// posts.deleteAll()
// .thenMany<Post> {
// posts.saveAll(
// arrayListOf(
// Post(null, "my first post", "content of my first post"),
// Post(null, "my second post", "content of my second post")
// )
// )
// }
.log()
.subscribe(null, null, { println("data initialization done.") })
}
}
thenMany
在Kotlin版本中不起作用,但是我使用concat
来吸引两个发布者,它可以按预期工作,我不知道为什么我的Kotlin版本不能按预期工作。
BWT,my sample codes可在我的Github下找到。