亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Spring 上重復 AWS S3 Bean,但找不到重復項

在 Spring 上重復 AWS S3 Bean,但找不到重復項

至尊寶的傳說 2022-06-08 17:45:04
我們剛剛在一個AmazonS3Client已經使用 Amazon S3 功能的項目上創建了一個帶有憑證的自定義項:import com.amazonaws.auth.AWSCredentialsProvider;import com.amazonaws.services.s3.AmazonS3Client;import com.amazonaws.services.s3.AmazonS3ClientBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;@Configurationpublic class S3Config {    @Bean    public static AmazonS3Client amazonS3Client(final AWSCredentialsProvider awsCredentialsProvider) {        return (AmazonS3Client) AmazonS3ClientBuilder.standard()                .withCredentials(awsCredentialsProvider)                .build();    }}它在所有其他項目上都運行良好,但由于某種原因,在啟動應用程序時,我們收到此錯誤:Parameter 0 of constructor in foo.bar.MyService required a single bean, but 2 were found:    - amazonS3Client: defined by method 'amazonS3Client' in class path resource [foo/bar/S3Config.class]    - amazonS3: defined in null在我們amazonS3定義了 Bean 的項目中,無處,絕對無處。那么,這個Service類的內容是什么呢?好吧,沒什么特別的:import com.amazonaws.services.s3.AmazonS3Client;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.io.ByteArrayInputStream;import java.net.URL;@Servicepublic class MyService {    private final AmazonS3Client s3Client;    @Autowired    public MyService(AmazonS3Client s3Client) {        this.s3Client = s3Client;    }    ...}它應該使用AmazonS3Client我們剛剛創建的,并且根據錯誤消息的第一個匹配它匹配它就好了。如果我刪除我的S3Config類,bean 復制錯誤就消失了。我們不想AmazonS3Client通過添加@Primary注解來強制項目使用我們的實現。那么,我們可能做錯了什么?
查看完整描述

1 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

經過幾個小時的調試,我們意識到 Service 的構造函數的參數名稱并沒有準確地命名為 Bean。我們重命名它,使其與 Bean 的名稱匹配:


@Service

public class MyService {

    private final AmazonS3Client s3Client; //Just fine


    @Autowired

    public MyService(AmazonS3Client amazonS3Client) { // Must match the bean name

        this.s3Client = amazonS3Client;

    }


    ...

}

并且 Bean 重復錯誤消失了。我們所要做的就是像 bean 一樣命名構造函數的參數。


查看完整回答
反對 回復 2022-06-08
  • 1 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號