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

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

问题描述:

我试图创建一个弹簧启动应用程序,我的课程将从文件src/main/resources/application.properties中读取。但由于某些原因,我不能让我的科特林与这些值工作(返回一个lateinit property url has not been initialized从`.properties`文件中检索值lateinit属性尚未初始化

的src /主/资源/ 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

为什么?如果您使用的是Spring Boot,那么为什么不使用创建数据源的默认方式?不知道你为什么要添加自己的>? –

+0

因为我似乎无法得到这项工作:/从来没有做过,但它创造了一个'h2'数据源,而不是使用我的属性 – Ivaro18

+0

@ M.Deinum编辑了这个问题,可能会再次出现错误 – Ivaro18

最常用的方法构造注射与@Value(适用于弹簧> = 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中使用一个属性即可。

+0

我现在试着这个,现在的问题是,我在所有的DAO上扩展了'BaseDAO'。使用'class SomeDAO:BaseDAO(){}'返回'在这一行的多个标记 - 没有为参数username传递值 - 没有为参数密码传递值 - 没有为参数url传递值 – Ivaro18