Spring-fu-Kofu: Невозможно подключить `NamedParameterJdbcTemplate` - PullRequest
1 голос
/ 23 февраля 2020

Я играю с функционалом Kofu Bean DSL. Я использую Spring-Data-JDB C с Spring- MVC и пытаюсь автоматически связать NamedParameterJdbcTemplate. Тем не менее, я получаю эту ошибку, что не было найдено bean-компонентов для него во время выполнения тестов. В подходе, основанном на аннотациях, нам не нужно предоставлять явный NamedParameterJdbcTemplate. Мой пример приложения здесь: https://github.com/overfullstack/kofu-mvc-jdbc. И PFB некоторые фрагменты кода из него:

val app = application(WebApplicationType.SERVLET) {
    beans {
        bean<SampleService>()
        bean<UserHandler>()
    }
    enable(dataConfig)
    enable(webConfig)
}
val dataConfig = configuration {
    beans {
        bean<UserRepository>()
    }
    listener<ApplicationReadyEvent> {
        ref<UserRepository>().init()
    }
}
val webConfig = configuration {
    webMvc {
        port = if (profiles.contains("test")) 8181 else 8080
        router {
            val handler = ref<UserHandler>()
            GET("/", handler::hello)
            GET("/api", handler::json)
        }
        converters {
            string()
            jackson()
        }
    }
}
class UserRepository(private val client: NamedParameterJdbcTemplate) {
    fun count() =
            client.queryForObject("SELECT COUNT(*) FROM users", emptyMap<String, String>(), Int::class.java)
}
open class UserRepositoryTests {
    private val dataApp = application(WebApplicationType.NONE) {
        enable(dataConfig)
    }
    private lateinit var context: ConfigurableApplicationContext
    @BeforeAll
    fun beforeAll() {
        context = dataApp.run(profiles = "test")
    }
    @Test
    fun count() {
        val repository = context.getBean<UserRepository>()
        assertEquals(3, repository.count())
    }
    @AfterAll
    fun afterAll() {
        context.close()
    }
}

Это ошибка:

Parameter 0 of constructor in com.sample.UserRepository required a bean of type 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate' in your configuration.

Пожалуйста, помогите, спасибо

1 Ответ

1 голос
/ 23 февраля 2020

Очевидно, что Кофу не выбирает источник данных из файла application.properties. Все должно быть декларативным и не подразумевать никаких дериваций. (В основном нет весенних волхвов c ?). Это сработало для меня:

val dataConfig = configuration {
    beans {
        bean {
            val dataSourceBuilder = DataSourceBuilder.create()
            dataSourceBuilder.driverClassName(“org.h2.Driver”)
            dataSourceBuilder.url(“jdbc:h2:mem:test”)
            dataSourceBuilder.username(“SA”)
            dataSourceBuilder.password(“”)
            dataSourceBuilder.build()
        }
        bean<NamedParameterJdbcTemplate>()
        bean<UserRepository>()
    }
    listener<ApplicationReadyEvent> {
        ref<UserRepository>().init()
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...