代码如下
@Component
public class MybatisUtils implements ApplicationContextAware {
private static SqlSessionTemplate sqlSessionTemplate;
private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
private static final String DEFAULT_LOCATION = "classpath:mapper/**/*.xml";
private static final Map<Class<?>, Object> CACHE = new HashMap<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
sqlSessionTemplate = applicationContext.getBean(SqlSessionTemplate.class);
}
@SuppressWarnings("unchecked")
public static <T> T getMapper(Class<T> mapperClass, String xmlPath) {
Object mapper = CACHE.get(mapperClass);
if (mapper != null) {
return (T) mapper;
}
if (StringUtils.isEmpty(xmlPath)) {
xmlPath = DEFAULT_LOCATION;
}
synchronized (CACHE) {
mapper = CACHE.get(mapperClass);
if (mapper != null) {
return (T) mapper;
}
try {
addXmlMappers(xmlPath);
} catch (IOException e) {
throw new RuntimeException("parse xml mapper error!");
}
mapper = sqlSessionTemplate.getMapper(mapperClass);
CACHE.put(mapperClass, mapper);
}
return (T) mapper;
}
private static void addXmlMappers(String location) throws IOException {
Resource[] resources = getResources(location);
Configuration configuration = sqlSessionTemplate.getConfiguration();
for (Resource resource : resources) {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(),
configuration,
resource.toString(),
configuration.getSqlFragments());
xmlMapperBuilder.parse();
}
}
private static Resource[] getResources(String location) {
try {
return resourceResolver.getResources(location);
} catch (IOException e) {
return new Resource[0];
}
}
}