簡體   English   中英

在服務層 class 中找不到 RestTemplate bean,即使我已經自動裝配了它

[英]RestTemplate bean is not found in the service layer class even though i have autowired it

當我運行應用程序時它工作正常但是當我構建應用程序時它拋出這個異常 - 沒有可用類型'org.springframework.web.client.RestTemplate'的合格bean:預計至少有1個bean符合自動裝配候選資格。

下面是代碼片段

請注意,我已經在主應用程序中創建了這個 bean,所以它的 scope 遍布整個應用程序,但仍然找不到。 任何人都可以提供一些幫助嗎?

@Autowired
RestTemplate restTemplateBean;

@Bean("restTemplateBean")
    public RestTemplate restTemplateBean(RestTemplateBuilder builder) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(new URL("file:src/main/resources/itsm_qa_api-keystore.jks"), "changeit".toCharArray()).build();

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory)
                .build();

        return builder
                .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
                .build();
    }

由於您已將 Bean 的特定名稱定義為"restTemplateBean" ,因此當您想要注入該特定 bean 時,您還需要限定 bean 名稱。

我想你可以這樣做:

@Autowired
@Qualifier("restTemplateBean")
RestTemplate restTemplate;

您也可以像這樣將 @Qualifier 與構造函數注入組合使用:

public class ClassA {

private RestTemplate restTemplate;

public ClassA(@Qualifier("restTemplateBean") RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

}

我忘記在測試配置 class 中添加一個 bean,這就是我收到此異常的原因。 謝謝大家

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM