这是我config.yml的一部分:
rhandsontable
我有一个用于解析的类:
#Authenctication
AuthenticationConfig:
AuthencticationType: LDAP
LDAPConfig:
LDAPUrl: ldap://localhost:389
ConnectionType: simple
LDAPSecurityConfig:
RootDN: cn=manager,dc=maxcrc,dc=com
RootPassword: secret
UserSearchDN: ou=People,dc=maxcrc,dc=com
GroupdSearchDB: ou=Groups,dc=maxcrc,dc=com
但是,当我跑步
public class YamlConfiguraiton {
private AuthenticationConfiguration AuthenticationConfig;
public void setAuthenticationConfig(AuthenticationConfiguration AuthenticationConfig) {
this.AuthenticationConfig = AuthenticationConfig;
}
public AuthenticationConfiguration getAuthenticationConfig() {
return this.AuthenticationConfig;
}
}
发生以下错误:
try(InputStream in = new FileInputStream(new File(ymalPath))) {
yamlConfig = yaml.loadAs(in, YamlConfiguraiton.class);
} catch (IOException e) {
e.printStackTrace();
}
为什么它抱怨找不到AuthenticationConfig属性,而AuthenticationConfig只是实例变量的名称?
更新 在将实例变量从“私有”更改为“公共”之后,SnakeYaml会识别它们,但这并不是我们可以肯定的。这些类不能识别为JavaBean。
更新 我找到了根本原因。这是命名约定。如果您希望SnakeYaml解析您的yaml文件,则必须遵守camelCase。 setter和getter方法的名称也很重要。假设有一个名为ldapConfig的私有实例变量,那么其getter和setter的名称必须为getLdapConfig和setLdapConfig,即使getLDAPConfig和setLDAPConfig也无法使用。
答案 0 :(得分:1)
该错误的主要原因是,您需要定义POJO类中Yaml文件中存在的所有属性(即YamlConfiguraiton
)。
您可以使用以下代码跳过未定义的属性。
Representer representer = new Representer();
representer.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new Constructor(YamlConfiguraiton.class), representer);
首先,在Yaml文件中将属性名称重命名为camelCase。
请参考以下代码:-
代码:-
public class YamlReadCustom {
private static String yamlPath = "/authentication.yaml";
public static void main(String[] args) {
Representer representer = new Representer();
representer.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new Constructor(Authentication.class), representer);
try(InputStream in = YamlReadCustom.class.getResourceAsStream (yamlPath)) {
Authentication authentication = yaml.loadAs(in, Authentication.class);
System.out.println(authentication.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
身份验证:-
public class Authentication {
private String authenticationConfig;
private String authencticationType;
private LdapConfig ldapConfig;
//getters and setters
}
LdapConfig:-
public class LdapConfig {
private String ldapUrl;
private String connectionType;
private Map<String, Object> ldapSecurityConfig;
//getters and setters
}
authentication.yaml
authenticationConfig:
authencticationType: LDAP
ldapConfig:
ldapUrl: ldap://localhost:389
connectionType: simple
ldapSecurityConfig:
rootDn: cn=manager,dc=maxcrc,dc=com
rootPassword: secret
userSearchDn: ou=People,dc=maxcrc,dc=com
groupdSearchDb: ou=Groups,dc=maxcrc,dc=com