spring框架:从classpath加载所有资源

时间:2015-02-10 00:52:11

标签: java spring resource-loading

我的spring应用程序中的classpath中有一个目录。如何使用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 个答案:

答案 0 :(得分:0)

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

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