在尝试映射嵌套java对象中的yml时遇到以下异常,是否还有任何一个异常,请建议:
org.springframework.beans.factory.BeanCreationException:错误 创建名为'alias'的bean:无法将属性绑定到Alias (prefix = alias,ignoreInvalidFields = false,ignoreUnknownFields = true, ignoreNestedProperties = FALSE);嵌套异常是 显示java.lang.NullPointerException 在org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:352) at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:303) 在org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder.rebind(ConfigurationPropertiesRebinder.java:100)
Caused by: java.lang.**NullPointerException**: null
应用alias.yml
alias:
name:
-
x: 123
-
x: 321
Alias.java
@Configuration
@ConfigurationProperties(prefix = "alias")
public class Alias {
private List<PropA> name = null;
public Alias() {}
public List<PropA> getName() {
return name;
}
public void setName(List<PropA> name) {
this.name = name;
}
}
AliasResolverImpl.java
@Component
@EnableConfigurationProperties
public class AliasResolverImplBack implements MapperInterface {
@Autowired
Alias aliases;
@Override
public List<Entity> resolve(List<Entity> request) throws AliasException {
System.out.println("In impl : "+aliases.toString());
return null;
}
}
ApplicationConfig.java
@SpringBootApplication(scanBasePackages = "com.ie.naukri.services.mnj.lookupService")
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
@EnableConfigurationProperties
public class ApplicationConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(final String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
final ApplicationContext applicationContext = SpringApplication.run(ApplicationConfig.class, args);
applicationContext.getBean(AliasResolverImpl.class).resolve(null);
}
}
PropA.java
@Configuration
@ConfigurationProperties(prefix="alias.name")
public class PropA {
private int x=0;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
@Override
public String toString() {
return "PropA [x=" + x + "]";
}
}
答案 0 :(得分:0)
这应该有效
@Configuration
@ConfigurationProperties(prefix = "alias")
public class Alias {
private List<PropA> name = null;
public Alias() {}
public List<PropA> getName() {
return name;
}
public void setName(List<PropA> name) {
this.name = name;
}
}
从PropA类中删除这些行
@Configuration
@ConfigurationProperties(prefix="alias.name")
您的PropA课程应该只是
public class PropA {
private int x=0;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
@Override
public String toString() {
return "PropA [x=" + x + "]";
}
}