首页 > 解决方案 > Spring JPA 扫描通用接口的用户实现

问题描述

我想为 Spring Data JPA 写一些入门。我在 kotlin 上有一个界面:

interface Converter<ResultType> {
fun convertList(values: List<String>): List<ResultType> {
    return values.map { convert(it) }
   }
    fun convert(value: String): ResultType
}

并从用户(将使用我的启动器的应用程序)包扫描此接口的实现到 Map <ResultType, implementation bean>。我的问题:

  1. 如何知道我应该扫描哪个包(理想情况下不要求用户添加一些属性)
  2. 以及如何构建地图我正在考虑使用反射。我还有其他选择吗?

可能有人知道 spring-data-jpa 如何扫描所有存储库。谢谢!

标签: javaspringkotlinreflection

解决方案


我找到了这个解决方案。

@Configuration
class ConverterAutoConfig(private val context: ApplicationContext ) {

@Bean("converters") // this need because spring already creates bean with this type, but instead type name as key spring injects class name
fun convertersMap(): Map<String, Converter<*>> {
    val converters: MutableMap<String, Converter<*>> = mutableMapOf()
    val beansOfType = context.getBeansOfType<Converter<*>>()
    beansOfType.forEach { (_, converter) ->
        val type: String = (converter.javaClass.genericInterfaces.first() as ParameterizedType)
                .actualTypeArguments.first().typeName
        converters[type] = converter
    }

    return converters
}
}

推荐阅读