【发布时间】:2018-03-31 18:42:00
【问题描述】:
我只是用 spring webflux 5.0.0 和 Kotlin 做了一些实验,我在从 application.yml 加载配置时遇到了问题
对于基础项目,我从这个例子开始 spring-kotlin-functional
但是只有手动加载 bean 和路由,而没有从配置文件中加载任何内容或示例如何以这种方式实现 @ConfigurationProperties 类的模拟。
我已经尝试在 bean 部分获取环境:
data class DbConfig(
var url: String = "",
var user: String = "",
var password: String = ""
)
fun beans(): BeanDefinitionDsl = beans {
bean {
//try to load config from path=db to data class DbConfig
env.getProperty("db", DbConfig::class.java)
}
bean<DBConfiguration>()
//controllers
bean { StatsController(ref()) }
bean { UserController(ref()) }
//repository
bean { UserRepository(ref()) }
//services
bean { StatsService(ref()) }
//routes
bean { Routes(ref(), ref()) }
bean("webHandler") {
RouterFunctions.toWebHandler(ref<Routes>().router(), HandlerStrategies.builder().viewResolver(ref()).build())
}
//view resolver
bean {
val prefix = "classpath:/templates/"
val suffix = ".mustache"
val loader = MustacheResourceTemplateLoader(prefix, suffix)
MustacheViewResolver(Mustache.compiler().withLoader(loader)).apply {
setPrefix(prefix)
setSuffix(suffix)
}
}
}
但Environment中只有系统属性
所以问题是如何从 application.yml 加载配置以及如何以这种功能样式实现 @ConfigurationProperties 的模拟?
我是否正确理解没有 spring-boot 所有注释(如@Bean、@Repository、@Transactional 和其他)都不适用于 Beans?
我的消息来源:github
2017 年 10 月 21 日更新
找到解决方案。问题与没有任何 BeanPostProcessor 的事实有关。在我包含这两个处理器之后:
bean<CommonAnnotationBeanPostProcessor>()
bean<ConfigurationClassPostProcessor>()
注释@Configuration、@Bean 和@PostConstruct 开始工作。但是注解@ConfigurationProperties只存在于spring-boot依赖中,而yml解析类我只在spring-boot-starter中找到..
在包含依赖 spring-boot-starter 并将 bean<ConfigurationPropertiesBindingPostProcessor>() 添加到 beans 部分后,注释 @ConfigurationProperties 开始工作,但来自 application.yml 的配置也不包括在内。所以我添加了这个部分:
val resource = ClassPathResource("/application.yml")
val sourceLoader = YamlPropertySourceLoader()
val properties = sourceLoader.load("main config", resource, null)
environment.propertySources.addFirst(properties)
到GenericApplicationContext 配置。现在一切都按我的预期工作,但包含一个依赖项spring-boot-starter。
完整代码示例:version with fixes
【问题讨论】:
标签: spring spring-mvc spring-boot kotlin