Skip to content

Autowire Spring beans #21

@shrralis

Description

@shrralis

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:

data class Entity(
    var id: Long,
    var nested: NestedEntity,
)

data class NestedEntity(
    var id: Long,
)

data class DTO(
    var id: Long,
    var nested: NestedDTO?,
    var nestedId: Long?,
)

data class NestedDTO(
    var id: Long,
)

@Konverter
@KComponent
interface EntityConverter {

    // here `dto.nested` is always `null`
    // instead, we want to use `dto.nestedId` to get an entity via `nestedRepository.findById(dto.nestedId)`
    fun convertToEntity(dto: DTO): Entity

    // here we want to fill the target `nested` using another Konverter,
    // so it would be `nestedConverter.convertToDTO(entity.nested)`
    fun convertToDTO(entity: Entity): DTO
}

So... I wonder, would it be the right approach to write something like this?

@Konverter
@KComponent
abstract class EntityConverter(
    // these should be `@Autowired` since the whole `EntityConverter` would be a `@Component`
    protected val nestedRepository: NestedRepository,
    protected val nestedConverter: NestedConverter,
) {

    @Konvert(
        mappings = [
            Mapping(target = "nested", expression = "nestedRepository.findById(it.nestedId)"),
        ]
    )
    fun convertToEntity(dto: DTO): Entity

    @Konvert(
        mappings = [
            Mapping(target = "nested", expression = "nestedConverter.convertToDTO(it.nested)"),
        ]
    )
    fun convertToDTO(entity: Entity): DTO
}

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    not plannedNot planned to be implemented unless a compelling reason is provided

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions