首页 > 解决方案 > 无法在 Spring Boot 中自动装配 resttemplate

问题描述

这是我的配置类。

@Component
public class Teamplate {
    @Bean(name="restProxy")
    public RestTemplate restProxy() {

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            String proxyHost = "10.123.10";
            String proxyPort = "8080";
            String proxyUser = "test";
            String proxyPassword = "test";
            Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)));
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    if (getRequestorType().equals(RequestorType.PROXY)) {
                        return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
                    }
                    return super.getPasswordAuthentication();
                }
            });
        requestFactory.setProxy(proxy);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }
}

这是我的主要课程

@Component
public class Call {
    @Autowired
    @Qualifier("restProxy")
    private RestTemplate restProxy;

    public void send() {
        // some code
        restProxy.exchange(requestEntity, responseType)
        //
    }
}

这是我的进口

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.Proxy.Type;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

这是我用于 resttemplate 的 pom

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

当我运行应用程序时,它说 com.xxCall 中的 Field restProxy 需要一个找不到的“org.springframework.web.client.RestTemplate”类型的 bean。

我无法自动装配我的resttemplate,我也尝试将其设为@primary,并使用@Qualifier(value="restProxy") 进行标记

标签: javaspring-bootjavabeansautowiredresttemplate

解决方案


推荐阅读