Java 当bean构造函数使用参数时Spring初始化失败
SpringBoot应用在尝试初始化此类时失败:Java 当bean构造函数使用参数时Spring初始化失败,java,spring,spring-boot,constructor,Java,Spring,Spring Boot,Constructor,SpringBoot应用在尝试初始化此类时失败: @Component public class Weather { private Map<Integer,Double> maxRainyDays; private Map<Integer, WeatherDays> totalDays; public Weather(Map<Integer, WeatherDays> totalDays, Map<Integer,Double> maxRa
@Component
public class Weather {
private Map<Integer,Double> maxRainyDays;
private Map<Integer, WeatherDays> totalDays;
public Weather(Map<Integer, WeatherDays> totalDays, Map<Integer,Double> maxRainyDays){
this.setMaxRainyDays(maxRainyDays);
this.setTotalDays(totalDays);
}
解决方法:
当我改为Weather()构造函数时,我解决了这个问题。当然,我必须使用setter来设置对象的属性
但是我需要理解发生的原因,因为您通过构造函数参数注入的集合(这里的映射)没有注册为SpringBean。这就是为什么要用@service
、@repository
等注释类,并将它们自动连接到其他类中。要修复此问题,您可以设置如下配置类:
@Configuration
public class BeanConfig {
@Bean
public Map<Integer, WeatherDays> totalDays() {
Map<Integer, WeatherDays> map = new HashMap<>();
map.put(1, WeatherDays.DRY);
return map;
}
@Bean
public Map<Integer, Double> maxRainyDays() {
Map<Integer, Double> map = new HashMap<>();
map.put(1, 0.2);
return map;
}
}
@配置
公共类BeanConfig{
@豆子
公共地图总天数(){
Map Map=newhashmap();
地图。放置(1,天气。干燥);
返回图;
}
@豆子
公共地图maxRainyDays(){
Map Map=newhashmap();
map.put(1,0.2);
返回图;
}
}
这个类看起来不应该是一个bean(服务对象);相反,它看起来像是一个数据对象。问题,为什么你考虑将天气注入组件?@ JoaNahanJOXX,因为我正在打包打包到其他服务中,让我解释一下。首先,当您在这个上下文中作为依赖项注入类时,您需要传递一个空的构造或一个带有参数的构造,它们需要作为bean注入,因为当Spring扫描所有组件时,它们应该注入一个空的构造或参数。示例公共天气(@Autowored Service){…}当一个类作为组件注入时,它或多或少类似于一个单例类。是的,您需要它。为此,您需要知道是否有必要创建一个名为Weather的组件,或者您需要从这个Weather类创建几个实例。很高兴知道!这就是您通常在spring服务中注入POJO或简单DTO的方式?如果你看chrylis的评论,那就太感谢你了。您的weather类是否要包含有状态数据并多次实例化?如果是这样,它不应该是一个bean,而应该使用一个服务类(作为bean)来设置它的状态并创建许多天气对象。
@Configuration
public class BeanConfig {
@Bean
public Map<Integer, WeatherDays> totalDays() {
Map<Integer, WeatherDays> map = new HashMap<>();
map.put(1, WeatherDays.DRY);
return map;
}
@Bean
public Map<Integer, Double> maxRainyDays() {
Map<Integer, Double> map = new HashMap<>();
map.put(1, 0.2);
return map;
}
}