2

当我使用 SnakeYaml 1.14 解析 config.yaml 时,我得到一个“找不到类异常”。以下是用于解析的代码。我已经使用 maven 来构建项目。

public class AppConfigurationReader 
{
    private static final  String CONFIG_FILE = "config.yaml";
    private static String fileContents = null;
    private static final Logger logger = LoggerFactory.getLogger(AppConfigurationReader.class);

    public static synchronized AppConfiguration getConfiguration() {
        return getConfiguration(false);
    }

    public static synchronized AppConfiguration getConfiguration(Boolean forceReload) {
        try {
            Yaml yaml = new Yaml();

            if(null == fileContents || forceReload) {
                fileContents = read(CONFIG_FILE);
            }
            yaml.loadAs(fileContents, AppConfiguration.class);
            return yaml.loadAs(fileContents, AppConfiguration.class);
        }
        catch (Exception ex) {
            ex.printStackTrace();
            logger.error("Error loading fileContents {}", ex.getStackTrace()[0]);
            return null;
        }
    }

    private static String read(String filename) {
        try {
            return new Scanner(new File(filename)).useDelimiter("\\A").next();
        } catch (Exception ex) {
            logger.error("Error scanning configuration file {}", filename);
            return null;
        }
    }
}
4

4 回答 4

6

可能我回复有点晚了,但它会在未来帮助其他人。

当您的类无法加载该类时会出现此问题,有时即使它也存在于您的类路径中。

我遇到了这个问题,可以这样处理。

package my.test.project;
import java.io.InputStream;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;
public class MyTestClass {
    public static void main(String[] args) {
        InputStream input = MyTestClass.class.getClassLoader().getResourceAsStream("test.yml");
        Yaml y = new Yaml(new CustomClassLoaderConstructor(MyTestClass.class.getClassLoader()));
        TestConfig test =y.loadAs(input, TestConfig.class);
        System.out.println(test);
    }
}

您需要使用CustomClassLoaderConstructor初始化 Yaml 对象,这将有助于在内部实际使用 bean 类之前加载它。

于 2019-08-30T16:19:15.203 回答
1

我也有这个,这是由于一组不正确的依赖关系。

我用过

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot</artifactId>
    </dependency>

当我应该使用

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

区别在于后者包括org.yaml:snakeyaml:jar:1.27:compile

于 2021-09-22T13:52:08.523 回答
0

我发现了一个类似的错误,但是转储了一个文件

您可以在 yaml.load 指令中写入类的完整名称。

例如,如果AppConfiguration.class在 中org.example.package1,您将编写如下内容:

yaml.loadAs(fileContents, org.example.package1.AppConfiguration.class);
于 2014-10-23T17:17:38.517 回答
0

似乎snakeyaml库不包含在您的jar文件中,您必须使用maven程序集插件而不仅仅是包,以便包含所有依赖项jar

于 2018-09-09T17:48:28.480 回答