1

我正在玩 Kofu 功能性 Bean DSL。我正在将 Spring-Data-JDBC 与 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.

请帮忙,谢谢

4

1 回答 1

1

显然 Kofu 没有从application.properties文件中选择数据源。一切都是声明性的,没有隐含的推导。(基本上没有Spring魔法)。这对我有用:

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()
    }
}
于 2020-02-23T10:18:19.843 回答