我尝试创建一个Spring引导应用程序,我的类将从文件src/main/resources/application.properties
中读取。但由于某些原因,我无法让我的Kotlin使用这些值(返回lateinit property url has not been initialized
。
src / main / resources / application.properties (注意,未在任何地方明确调用?)
spring.datasource.url=someUrl
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=org.postgresql.Driver
科特林
@Component
open class BaseDAO() {
@Autowired
lateinit var datasource: DataSource;
}
新错误
kotlin.UninitializedPropertyAccessException: lateinit property datasource has not been initialized
at quintor.rest.persistence.BaseDAO.getDatasource(BaseDAO.kt:18) ~[classes/:na]
at quintor.rest.persistence.EventDAO.getMultipleEvents(EventDAO.kt:45) ~[classes/:na]
at quintor.rest.persistence.EventDAO.getComingOpenEvents(EventDAO.kt:98) ~[classes/:na]
at quintor.rest.persistence.EventService.getComingEvents(EventService.kt:23) ~[classes/:na]
at quintor.rest.spring.EventsController.getEvents(EventsController.kt:37) ~[classes/
应用
@SpringBootApplication
open class Application : SpringBootServletInitializer(){
companion object {
@JvmStatic fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args);
}
@Override
protected fun configure(app:SpringApplicationBuilder):SpringApplicationBuilder{
return app.sources(Application::class.java);
}
}
}
EventDAO(在错误中提到)只是扩展BaseDAO并使用datasource
答案 0 :(得分:2)
我们在项目中最常见的方法是使用@Value
构造函数注入(与Spring&gt; = 4.3一起使用):
@PropertySource("classpath:config.properties")
@Component
open class BaseDAO(
@Value("\${jdbc.url}") private val url: String,
@Value("\${jdbc.username}") private val username: String,
@Value("\${jdbc.password}") private val password: String
) {
val config: HikariConfig = HikariConfig()
init {
Class.forName("org.postgresql.Driver").newInstance()
config.jdbcUrl = url
config.username = username
config.password = password
config.minimumIdle = 2
config.maximumPoolSize = 20
config.idleTimeout = 60000
}
}
我认为你不需要这个companion object
来创建一个池,只需在你的DAO中使用一个属性。