简体   繁体   中英

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 . But for some reason I can't get my Kotlin to work with these values (returning a lateinit property url has not been initialized .

src/main/resources/application.properties (note, not explicitly called anywhere?)

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

The most common way we're doing it in our project is by constructor injection with @Value (works with 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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