java - 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>。我的问题:
- 如何知道我应该扫描哪个包(理想情况下不要求用户添加一些属性)
- 以及如何构建地图我正在考虑使用反射。我还有其他选择吗?
可能有人知道 spring-data-jpa 如何扫描所有存储库。谢谢!
解决方案
我找到了这个解决方案。
@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
}
}
推荐阅读
- .net-core - 无法在 c# dotnetcore 中调用 JNI 导出的函数
- perl - Perl Net::SMTP 在 Fedora 上失败
- python - PyQt6 - QPalette 无法在 mdiArea 窗口中正常工作
- cuda - MIO/L1TEX 的“长”和“短”记分牌是什么?
- angular - Jest - 在 jest.setTimeout.Error 指定的 5000 毫秒超时内未调用异步回调
- node.js - 如何使用 sendGrid 将使用 react-pdf 包生成的 PDF 作为附件附加到电子邮件
- wso2 - WSO2 EI 6.4 和错误原因:org.apache.ws.security.WSSecurityException
- amazon-web-services - 找不到我创建的 AWS EC2 存储磁盘
- html - 为什么我的
- Bootstrap 5中的元素总是溢出?
- sql - 将类别分配给产品而无需重复