我们刚刚使用已使用 Amazon S3 功能的项目上的凭证创建了一个自定义 AmazonS3Client
:
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;
@Configuration
public 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;
@Service
public class MyService {
private final AmazonS3Client s3Client;
@Autowired
public MyService(AmazonS3Client s3Client) {
this.s3Client = s3Client;
}
...
}
它应该使用我们刚刚创建的AmazonS3Client
,并且根据错误消息的第一个匹配,它匹配得很好。如果我删除 S3Config
类,bean 重复错误就会消失。
我们不想通过添加 @Primary
注释来强制项目使用我们的 AmazonS3Client
实现。
那么,我们可能做错了什么?
最佳答案
经过几个小时的调试,我们意识到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 一样命名构造函数的参数。
关于java - Spring 上有重复的 AWS S3 Bean,但找不到重复的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54584880/