如何在应用程序启动弹簧启动时读取文件并加载对象

时间:2016-04-03 17:11:07

标签: java spring spring-boot

我的Yaml文件包含配置,例如导航项,插件名称等。目前我在组件类中读取此文件并且必须在每个类中注入它,是否有任何方法可以在应用程序启动时读取并加载此.yml文件使其可用于应用程序并创建html文件而无需注入每个类和在每种方法中调用它?

这就是我在阅读文件的方式。

List<Manifest> readManifestYamlFiles(String path) {
        // adding the files content to the list
        List<Manifest> manifestFiles = []
        // variable to hold the fileContents
        String fileContents = ""
        // recursively looping over the plugins directory to read the manifest.yml file
        println path
        new File(path).eachDirRecurse() { dir ->
            // looking for only .yml file
            dir.eachFileMatch(~/.*.yml/) { file ->
                // set the fileContent to the variable
                fileContents = new File(file.getPath()).text
                // map manifest.yml file content
                Manifest manifest = yamlUtility.mapYamlToObject(fileContents, Manifest.class, new Manifest())
                // add content of each file to the list
                manifestFiles.add(manifest);
            }
        }
        return manifestFiles
    }

1 个答案:

答案 0 :(得分:0)

这听起来像是@ConfigurationProperties

的理想用例