[英]Retrieve values from `.properties` file | lateinit property has not been initialized
I'm trying to create a spring boot application were my class will read from a file src/main/resources/application.properties
. 我正在尝试创建一个Spring Boot应用程序,我的班级将从文件
src/main/resources/application.properties
读取。 But for some reason I can't get my Kotlin to work with these values (returning a lateinit property url has not been initialized
. 但是由于某种原因,我无法使我的Kotlin使用这些值(返回的
lateinit property url has not been initialized
。
src/main/resources/application.properties (note, not explicitly called anywhere?) src / main / resources / application.properties (注意,未在任何地方显式调用吗?)
spring.datasource.url=someUrl
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=org.postgresql.Driver
Kotlin 科特林
@Component
open class BaseDAO() {
@Autowired
lateinit var datasource: DataSource;
}
new error 新错误
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/
Application 应用
@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 (mentioned in the error) is just extending the BaseDAO and using the datasource
EventDAO(错误中提到)只是扩展BaseDAO并使用
datasource
The most common way we're doing it in our project is by constructor injection with @Value
(works with Spring >= 4.3): 我们在项目中执行此操作的最常见方法是使用
@Value
进行构造函数注入(适用于Spring> = 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
}
}
I think you don't need this companion object
to create a pool, just use a property inside your DAO. 我认为您不需要此
companion object
来创建池,只需在DAO中使用属性即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.