字段 restTemplate 需要一个 bean,但找到了 2 个

Field restTemplate required a single bean, but 2 were found

我正在尝试解决此代码的问题:

import io.christdoes.wealth.tracker.controller.error.ReCaptchaInvalidException;
import io.christdoes.wealth.tracker.controller.error.ReCaptchaUnavailableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.regex.Pattern;

@Service("captchaService")
public class CaptchaService implements ICaptchaService {
    private final static Logger LOGGER = LoggerFactory.getLogger(CaptchaService.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private CaptchaSettings captchaSettings;

    @Autowired
    private ReCaptchaAttemptService reCaptchaAttemptService;

    @Autowired
    private RestOperations restTemplate;

    private static final Pattern RESPONSE_PATTERN = Pattern.compile("[A-Za-z0-9_-]+");

    @Override
    public void processResponse(final String response) {
        LOGGER.debug("Attempting to validate response {}", response);

        if (reCaptchaAttemptService.isBlocked(getClientIP())) {
            throw new ReCaptchaInvalidException("Client exceeded maximum number of failed attempts");
        }

        if (!responseSanityCheck(response)) {
            throw new ReCaptchaInvalidException("Response contains invalid characters");
        }

        final URI verifyUri = URI.create(String.format("https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s", getReCaptchaSecret(), response, getClientIP()));
        try {
            final GoogleResponse googleResponse = restTemplate.getForObject(verifyUri, GoogleResponse.class);
            LOGGER.debug("Google's response: {} ", googleResponse.toString());

            if (!googleResponse.isSuccess()) {
                if (googleResponse.hasClientError()) {
                    reCaptchaAttemptService.reCaptchaFailed(getClientIP());
                }
                throw new ReCaptchaInvalidException("reCaptcha was not successfully validated");
            }
        } catch (RestClientException rce) {
            throw new ReCaptchaUnavailableException("Registration unavailable at this time.  Please try again later.", rce);
        }
        reCaptchaAttemptService.reCaptchaSucceeded(getClientIP());
    }

    private boolean responseSanityCheck(final String response) {
        return StringUtils.hasLength(response) && RESPONSE_PATTERN.matcher(response).matches();
    }

    @Override
    public String getReCaptchaSite() {
        return captchaSettings.getSite();
    }

    @Override
    public String getReCaptchaSecret() {
        return captchaSettings.getSecret();
    }

    private String getClientIP() {
        final String xfHeader = request.getHeader("X-Forwarded-For");
        if (xfHeader == null) {
            return request.getRemoteAddr();
        }
        return xfHeader.split(",")[0];
    }
}

错误

web - 2019-09-25 14:20:18,416 [restartedMain] INFO  o.a.c.c.StandardService - Stopping service [Tomcat]
web - 2019-09-25 14:20:18,491 [restartedMain] ERROR o.s.b.d.LoggingFailureAnalysisReporter - 

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

Description:

Field restTemplate in io.christdoes.wealth.tracker.captcha.CaptchaService required a single bean, but 2 were found:
    - org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer#0: defined in null
    - org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer#1: defined in null


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed


Process finished with exit code 0

我一直在努力解决这个问题,但找不到解决方法。我不断收到上述错误。

我搜索了 SO 和 Github,其中报告了类似的错误但没有帮助。有人指出这是一个依赖性问题,同时具有 spring-web 和 hateoas 可能是问题所在。我删除了网络但问题仍然存在。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

虽然早期的项目 spring-boot 依赖版本 2.0.4 有效,但我目前使用的是最新版本 2.1.8。我不想恢复到早期版本,因为我有最近使用的代码 2.1.8.

我该怎么做才能克服这个挑战?

您可以检查其中一种方法:

  1. 第一个

    是删除 spring boot ,因为它是 spring-boot-starter-hateoas

    我认为这导致两次创建 bean

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    

    然后清理并重新安装您的项目。 运行 再次.

  2. 第二种解决方案

    创建您自己的 RestTemplate bean,因为这最后实现了 RestOperations 接口: 并将其用作以下内容:

    在配置中 class 创建一个 bean:

    @Bean
    public RestTemplate myRestTemplate(RestTemplateBuilder builder) {
    
        return builder
                 .setConnectTimeout(10000)
                 .setReadTimeout(10000)
                 .build();
    }
    

    然后替换自动装配的

    @Autowired
    private RestOperations restTemplate; 
    

    来自:

    @Autowired
    private RestTemplate myRestTemplate;
    

我使用 RestTemplateBuilder 而不是 RestTemplate 解决了这个问题。 在我从配置文件中删除我的@Bean RestTemplate 创建之前。

 private RestTemplate restTemplate;
   public MyClass(RestTemplateBuilder restTemplate){
     this.restTemplate = restTemplate.build();
    }