Bin*_*mas 12 java spring classpath
我想通过使用上下文类加载器将它们作为资源加载来读取一堆文本文件.
URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("folder/foo.txt");
Run Code Online (Sandbox Code Playgroud)
有没有办法获得名称与给定模式匹配的资源列表?例如:
URL[] matchingUrls = someLibrary.getMatchingResources("folder/*.txt");
Run Code Online (Sandbox Code Playgroud)
像Spring这样的库可以扫描类路径以查找具有给定注释的类,所以我想知道是否有类似的东西加载一堆资源.
小智 13
只需使用:
@Value("classpath:folder/*.xml")
Resource[] resources;
Run Code Online (Sandbox Code Playgroud)
来自"Binil Thomas"的评论是在正确的轨道上,我正在寻找确认Spring的PathMatchingResourcePatternResolver可以从Java Config中使用,以便我可以将生成的"资源"列表提供给Spring Hibernate SessionFactory.mappingLocations而无需更新列表休眠的*的.hbm.xml文件每加入一个新的映射文件的时间.我可以用下面的代码的PathMatchingResourcePatternResolver来实现这一点:
import org.hibernate.SessionFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
...
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
Resource [] mappingLocations = patternResolver.getResources("classpath*:mappings/**/*.hbm.xml");
sessionFactory.setMappingLocations(mappingLocations);
Run Code Online (Sandbox Code Playgroud)
奇迹般有效.
Spring支持ant-style类路径资源匹配.
http://static.springsource.org/spring/docs/2.5.x/reference/resources.html
例如: classpath:com/mycompany/**/applicationContext.xml, /WEB-INF/*-context.xml
看看你是否可以在项目中使用spring.如果不可能,那么你总是可以下载源代码来看看他们在做什么,并自己做:)
小智 5
你可以试试corn-cps
List<URL> resources = CPScanner.scanResources(new PackageNameFilter("net.sf.corn.cps.*"), new ResourceNameFilter("*.xml"));
Run Code Online (Sandbox Code Playgroud)
在你的 pom.xml 中使用下面的依赖
<dependency>
<groupId>net.sf.corn</groupId>
<artifactId>corn-cps</artifactId>
<version>1.0.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)