SpringBoot: MyBatis创建自定义ObjectFactory

1.定义自己的继承自DefaultObjectFactory类的工厂类:

package cn.edu.tju.factory;

import org.apache.ibatis.reflection.ReflectionException;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

import java.lang.reflect.Constructor;
import java.util.*;

public class MyObjectFactory extends DefaultObjectFactory {
    @Override
    public <T> T create(Class<T> type) {
        System.out.println("无参构造方法被调用:"+type.getName());
        return super.create(type, null, null);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {

        // we know types are assignable
        System.out.println("有参构造方法被调用:"+type.getName());
        return super.create(type,constructorArgTypes,constructorArgs);
    }

    @Override
    public void setProperties(Properties properties) {
        // no props for default
    }

    @Override
    public <T> boolean isCollection(Class<T> type) {
        return super.isCollection(type);
    }
}

2.定义转换器类:

package cn.edu.tju.converter;

import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;


@Component
@ConfigurationPropertiesBinding
public class ObjectFactoryConverter implements Converter<String, ObjectFactory> {
    @Override
    public ObjectFactory convert(String source) {
        try {
            ObjectFactory objectFactory=(ObjectFactory) Class.forName(source).newInstance();
            return objectFactory;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return null;
    }
}

3.在SpringBoot程序的配置文件application.properties增加自定义工厂类

mybatis.configuration.object-factory=cn.edu.tju.factory.MyObjectFactory

你可能感兴趣的:(SpringBoot,MyBatis,java,spring,spring,boot)