首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >字段restTemplate只需要一个bean,但是找到了两个

字段restTemplate只需要一个bean,但是找到了两个
EN

Stack Overflow用户
提问于 2019-09-25 13:42:54
回答 2查看 4.4K关注 0票数 1

我试图用这个代码来解决一个问题:

代码语言:javascript
运行
复制
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];
    }
}

错误

代码语言:javascript
运行
复制
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的问题,也是仇恨的问题。我删除了网络,但问题仍然存在。

代码语言:javascript
运行
复制
<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启动依赖项的早期项目工作正常,但我目前使用的是最新版本的2.1.8。我不想回到以前的版本,因为我有最近的代码,我只使用2.1.8

我该怎么办才能通过这个挑战?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-25 14:22:06

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

  1. 第一个: 是删除spring boot,因为它是spring-boot-starter-hateoas的层次依赖关系 其中我认为这两次导致了bean的创建 org.springframework.boot弹簧-启动-启动-web 然后清理,并重新安装您的项目。再跑一次。
  2. 第二个解决方案: 创建您自己的RestTemplate bean,因为这是最后一次实现RestOperations接口:并将其用作folow: 在config类中创建一个bean: @Bean公共RestTemplate myRestTemplate(RestTemplateBuilder构建器){返回构建器.setConnectTimeout(10000) .setReadTimeout(10000) .build();} 然后更换自动头发 @自动头发的私人RestOperations restTemplate; 通过: @自动头发的私人RestTemplate myRestTemplate;
票数 1
EN

Stack Overflow用户

发布于 2019-10-31 15:08:33

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

代码语言:javascript
运行
复制
 private RestTemplate restTemplate;
   public MyClass(RestTemplateBuilder restTemplate){
     this.restTemplate = restTemplate.build();
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58099818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档