你需要使用一个ResourcePatternResolver http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/support/ResourcePatternResolver.html翻译classpath*:dozer/**/*.dzr.xml
into a Resource[]
。您可以使用 2 个主要选项。
- 注入
ApplicationContext
到你的配置类中,将其转换为ResourcePatternResolver
并使用getResources
方法。 Al Spring 默认应用程序上下文实现实现了ResourcePatternResolver
界面。
- 创建一个
PathMatchingResourcePatternResolver
有或没有前面提到的上下文。
- Use the ResourcePatternUtils http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/support/ResourcePatternUtils.html与注射的
ResourceLoader
.
使用 ResourcePatternUtils
@Configuration
public class MyConfiguration {
@Autowired
private ResourceLoader resourceLoader;
public DozerBeanMapperFactoryBean mapper() throws IOException {
DozerBeanMapperFactoryBean mapper = new DozerBeanMapperFactoryBean();
// ResourceLoader is allowed to be null when using the ResourceLoaderUtils.
ResourcePatternResolver resolver = ResourceLoaderUtils.getResourcePatternResolver(resourceLoader);
Resource[] mappingFiles = resolver.getResources("classpath*:dozer/**/*.dzr.xml");
mapper.setMappingFiles(mappingFiles);
return mapper;
}
}
最后一种方法的优点是您不受束缚PathMatchingResourcePatternResolver
但只是界面。实用程序类根据注入来确定ResourceLoader
它能做什么。人们应该更喜欢这种加载资源的方式。
使用应用程序上下文
@Configuration
public class MyConfiguration {
@Autowired
private ApplicationContext context;
public DozerBeanMapperFactoryBean mapper() throws IOException {
DozerBeanMapperFactoryBean mapper = new DozerBeanMapperFactoryBean();
Resource[] mappingFiles = ((ResourcePatternResolver) context).getResources("classpath*:dozer/**/*.dzr.xml");
mapper.setMappingFiles(mappingFiles);
return mapper;
}
}
使用 PathMatchingResourcePatternResolver
@Configuration
public class MyConfiguration {
private PathMatchingPatternResolver resolver = new PathMatchingPatternResolver();
public DozerBeanMapperFactoryBean mapper() throws IOException {
DozerBeanMapperFactoryBean mapper = new DozerBeanMapperFactoryBean();
Resource[] mappingFiles = resolver.getResources("classpath*:dozer/**/*.dzr.xml");
mapper.setMappingFiles(mappingFiles);
return mapper;
}
}
或者如果您想重用已经存在的ResourceLoader
略有不同的版本:
@Configuration
public class MyConfiguration {
@Autowired
private ResourceLoader resourceLoader;
public DozerBeanMapperFactoryBean mapper() throws IOException {
DozerBeanMapperFactoryBean mapper = new DozerBeanMapperFactoryBean();
Resource[] mappingFiles = new PathMatchingPatternResolver(resourceLoader).getResources("classpath*:dozer/**/*.dzr.xml");
mapper.setMappingFiles(mappingFiles);
return mapper;
}
}