工厂设计的实现,在Spring Boot中遇到此错误

问题描述 投票:0回答:1

您好,我在@DruidKuma的一些指南的帮助下创建了一个工厂:Implement a simple factory pattern with Spring 3 annotations

我按如下方式创建了工厂:

@Component
public class ValidatorFactory {
    @Autowired
    private List<Validator> validators;

    private static final Map<String, Validator> validatorMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void setValidatorMap() {
        for (Validator validator : validators) {
            validatorMap.putIfAbsent(validator.getCountry().name(), validator);
        }
    }

    public Validator getValidator(Value v) {
        return validatorMap.get(v.name());
    }
}

但是当我尝试启动应用程序时,出现此错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field validators in com.abc.factory.ValidatorFactory required a bean of type 'java.util.List' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'java.util.List' in your configuration.

我从帮助我的链接中了解到,spring应该自动创建bean。有人可以帮我吗?

java spring spring-boot factory factory-pattern
1个回答
0
投票
根据您的代码:

@Autowired private List<Validator> validators;

Spring尝试查找类型为Validator的bean,如果找不到任何bean,则抛出错误required a bean of type 'java.util.List' that could not be found.

要解决此问题,请确保类路径中有Validator类型的Bean,并且正在使用Spring容器对其进行扫描,例如使用@ComponentScan

© www.soinside.com 2019 - 2024. All rights reserved.