简体   繁体   English

当 bean 构造函数使用参数时,Spring init 失败

[英]Spring init failing when bean constructor using parameters

SpringBoot app fails while trying to initialize this class: SpringBoot 应用程序在尝试初始化此类时失败:

@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);

}

The error:错误:

Parameter 0 of constructor in SolarSystem.Models.Weather required a bean of type 'SolarSystem.Utilities.WeatherDays' that could not be found. SolarSystem.Models.Weather 中构造函数的参数 0 需要一个无法找到的类型为“SolarSystem.Utilities.WeatherDays”的 bean。

The mentioned bean is already defined (in the same basepackage):提到的 bean 已经定义(在同一个 basepackage 中):

public enum WeatherDays {

RAINY,
MILD,
DRY,
MAX_RAIN}

Workaround:解决方法:

When I changed to Weather() constructor I solved the issue.Of course I had to use setters to set the properties of the object.当我更改为 Weather() 构造函数时,我解决了这个问题。当然,我必须使用 setter 来设置对象的属性。

But I need to understand the reasons why happened但我需要了解发生的原因

Because the collections (Map here) you are injecting via constructor parameter aren't registered as Spring beans.因为您通过构造函数参数注入的集合(此处为 Map)未注册为 Spring bean。 This is why you would annotate class with @service , @repository , etc and have them autowired into other classes.这就是为什么您要用@service@repository等注释类并将它们自动装配到其他类中的原因。 To fix, you can set up a config class like such:要修复,您可以像这样设置一个配置类:

@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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM