SnakeYaml 类未找到异常

abc*_*bcd 1 snakeyaml maven-3

当我使用 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ewL 8

我也遇到过这个问题,这是由于依赖关系集不正确造成的。

我曾经用过

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot</artifactId>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

当我应该使用

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

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


Sha*_*ngh 5

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

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

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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


kiu*_*_88 0

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

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

例如,如果AppConfiguration.class是 in org.example.package1,您可以编写如下内容:

yaml.loadAs(fileContents, org.example.package1.AppConfiguration.class);
Run Code Online (Sandbox Code Playgroud)