解决 Spring xml方式读取yml配置文件 java.nio.charset.MalformedInputException 异常
问题描述:
Spring通过applicationContext.xml配置yaml文件读取时出错
错误异常:
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0': Cannot resolve reference to bean 'yamlProperties' while setting bean property 'properties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'yamlProperties' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0': Cannot resolve reference to bean 'yamlProperties' while setting bean property 'properties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'yamlProperties' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1
分析原因:yml配置文件中文解析异常,字符集异常
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'yamlProperties' defined in class path resource [applicationContext.xml]
Spring配置文件applicationContext.xml中YamlPropertiesFactoryBean注入失败
nested exception is org.yaml.snakeyaml.error.YAMLException:yaml配置文件解析失败
java.nio.charset.MalformedInputException:NIO读取文件编码异常
解决方法:将yml配置文件字符集修改为UTF-8即可