我們剛剛在一個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 一樣命名構造函數的參數。
添加回答
舉報
0/150
提交
取消