-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Autowire Spring beans #21
Comments
Well, I've just tried my assumption and got an error:
I also tried this approach: @Konverter
@KComponent
interface EntityConverter {
@set:Autowired
var nestedConverter: NestedConverter
@set:Autowired
var nestedRepository: NestedRepository
} But it also doesn't not work, result Konverter doesn't implement the abstract property, I've expected to see there something like object EntityConverterImpl : EntityConverter {
override lateinit var nestedConverter: NestedConverter
override lateinit var nestedRepository: NestedRepository
....
} |
Hi @shrralis, right now using other beans is not directly possible with Konvert. You can use workarounds (see below), but, you should really think about if you want to include that kind of logic into mapping code. From my experience, mapping code should be as simple as possible. The entity to DTO direction is already possible without any extra effort, just define a mapping function, @Konverter
interface EntityConverter {
fun convertToDTO(entity: Entity): DTO
fun convertToDTO(nestedEntity: NestedEntity): NestedDTO
} Regarding the workaround for the other way around where you need a bean, you can e.g. access the application context:
@Component
class YourApplicationAwareBean : ApplicationContextAware {
companion object {
lateinit var applicationContext: ApplicationContext
}
override fun setApplicationContext(applicationContext: ApplicationContext) {
YourApplicationAwareBean.applicationContext = applicationContext
}
}
@Konverter
interface EntityConverter {
@Konvert(
mappings = [
Mapping(target = "nested", expression = "findById(it.nestedId)"),
]
)
fun convertToEntity(dto: DTO): Entity
fun findById(nestedId: Long?): NestedEntity? {
return YourApplicationAwareBean.applicationContext.getBean(NestedRepository::class.java).findById(nestedId)
}
} Not the best solution, but depending on your context this might work well enough. |
@mcarleio thanks for the workaround! |
Hey!
It's more a question or feature request rather than an issue.
Is there an opportunity to use Spring Beans within Kovert converters?
Example code:
So... I wonder, would it be the right approach to write something like this?
I was considering using the
TypeConverter
for that but I'm not sure if I would be able to achieve what I need with that.The text was updated successfully, but these errors were encountered: