繁体   English   中英

从`.properties`文件中检索值| lateinit属性尚未初始化

[英]Retrieve values from `.properties` file | lateinit property has not been initialized

我正在尝试创建一个Spring Boot应用程序,我的班级将从文件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

我们在项目中执行此操作的最常见方法是使用@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
    }

}

我认为您不需要此companion object来创建池,只需在DAO中使用属性即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM