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

时间:2019-09-25 13:42:54

标签: spring spring-boot spring-security resttemplate spring-hateoas

我正在尝试解决以下代码问题:

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,也有仇恨的问题。我删除了网络,但问题仍然存在。

<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>

尽管较早的项目具有版本2.0.4的spring-boot依赖性,但我目前使用的是最新版本2.1.8。我不想恢复到较早的版本,因为我有我刚使用过的2.1.8代码。

我要怎么做才能克服这一挑战?

2 个答案:

答案 0 :(得分:1)

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

  1. 第一个

    是要删除 <DataGrid Name="matrix" dataGrid2D:ItemsSource.Array2D="{Binding Matrix, NotifyOnTargetUpdated = true}" IsReadOnly="True"> ,因为它是 spring boot

    我认为这会导致两次创建bean

    spring-boot-starter-hateoas

    然后清理,然后重新安装项目。再次运行。

  2. 第二个解决方案

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

    在配置类中创建一个bean:

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

    然后更换自动接线

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

    作者:

    @Autowired
    private RestOperations restTemplate; 
    

答案 1 :(得分:0)

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

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