All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.linpeilie.mapstruct.SpringConverterFactory Maven / Gradle / Ivy

The newest version!
package io.github.linpeilie.mapstruct;

import io.github.linpeilie.AbstractCachedConverterFactory;
import io.github.linpeilie.BaseCycleAvoidingMapper;
import io.github.linpeilie.BaseMapMapper;
import io.github.linpeilie.BaseMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ResolvableType;

public class SpringConverterFactory extends AbstractCachedConverterFactory {

    private final ApplicationContext applicationContext;

    public SpringConverterFactory(final ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public  BaseMapper findMapper(final Class sourceType, final Class targetType) {
        ResolvableType type = ResolvableType.forClassWithGenerics(
            BaseMapper.class, sourceType, targetType);
        String[] beanNames = applicationContext.getBeanNamesForType(type);
        if (beanNames.length == 0) {
            return null;
        }
        return (BaseMapper) applicationContext.getBean(beanNames[0]);
    }

    @Override
    protected  BaseMapMapper findMapMapper(final Class source) {
        ResolvableType type = ResolvableType.forClassWithGenerics(
            BaseMapMapper.class, source);
        String[] beanNames = applicationContext.getBeanNamesForType(type);
        if (beanNames.length == 0) {
            return null;
        }
        return (BaseMapMapper) applicationContext.getBean(beanNames[0]);
    }
}