2015-02-10 92 views
0

我在我的弹簧应用程序的类路径中有一个目录。如何使用ResouceLoader加载该目录中的所有文件。弹簧框架:从类路径加载所有资源

// bean for test context 
public class DatabaseLoader { 
    @Autowired 
    protected ResourceLoader myLoader; 

    private Logger log = LoggerFactory.getLogger(this.getClass()); 

    @PostConstruct 
    public void init() throws IOException, FileNotFoundException { 
     Resource[] resources = myLoader.getResource("classpath:fixtures/*.sql"); 
     //codepopulate in memory db with all test fixtures 
     for (Resource r: resources) { 
      //populate in memory db with data in this resource. 
     } 
    } 
} 
+1

看一看http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/ core/io/support/PathMatchingResourcePatternResolver.html – fateddy 2015-02-10 02:04:19

+0

fateddy:任何代码示例? – riship89 2015-02-11 18:45:12

+0

找到下面的答案代码示例。如果这解决了您的问题,请接受答案。 – fateddy 2015-05-09 18:14:22

回答

0

PathMatchingResourcePatternResolver能够装载使用特殊classpath*:前缀和/或内部Ant风格的正则表达式的资源。例如。加载匹配的*.sql后缀的类路径中的所有资源,尝试下面的代码片段:

PathMatchingResourcePatternResolver loader = new PathMatchingResourcePatternResolver(); 
Resource[] resources = loader.getResources("classpath:/*.sql"); 
for (Resource resource : resources) { 
    // process resource 
}