没有发现SnakeYaml类异常

时间:2014-10-20 10:06:35

标签: maven-3 snakeyaml

当我使用SnakeYaml 1.14解析config.yaml时,我得到一个" Class not found exception"。以下是用于解析的代码。我用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;
        }
    }
}

3 个答案:

答案 0 :(得分:0)

我发现了类似的错误dumping a file

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

例如,如果AppConfiguration.class位于org.example.package1,您可以写下这样的内容:

yaml.loadAs(fileContents, org.example.package1.AppConfiguration.class);

答案 1 :(得分:0)

jar文件中似乎没有包含snakeyaml库之类的东西,您必须使用maven程序集插件而不是仅使用package,这样才能包含所有依赖项jars

答案 2 :(得分:0)

也许我来晚了,但将来会有所帮助。

当您的类无法加载该类时,有时甚至在类路径中也存在该类时,就会出现此问题。

我遇到了这个问题,可以通过这种方式进行处理。

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类。