Spring Autowire是否按Java Config的方法名称命名

nik*_*hil 4 java spring

我们ApplicationConfig像这样定义了一些bean-

@Bean
S3Repository s3Repository() {
    AmazonS3 s3 = new AmazonS3Client(s3AdminReadWriteCreds());
    return new S3Repository(s3);
}

@Bean
S3Repository s3PrivateContentRepository() {
    AmazonS3 s3 = new AmazonS3Client(readOnlyS3Creds());
    return new S3Repository(s3);
}

@Bean
S3Repository s3SyncFilesContentRepository() {
    AmazonS3 s3 = new AmazonS3Client(readOnlySpecificBucketCreds());
    return new S3Repository(s3);
}
Run Code Online (Sandbox Code Playgroud)

这就是它们在代码中的用法-

public class AssetReader {
@Autowired
private S3Repository s3PrivateContentRepository;
.... used inside the class ....
}
Run Code Online (Sandbox Code Playgroud)

同样,其他bean的名称与预期产生它们的方法相同。

该应用程序运行良好,但是对此我感到有些惊讶,我不确定是否带有Admin凭据的bean是否会偶然地自动连接到任何地方,或者由于Spring的一些实现细节而是否连接了正确的bean?

我认为,如果自动装配可能产生歧义,则必须指定一个限定符。假设这能按预期进行,那么我们是否有任何理由使这些bean合格?

Ger*_*cso 6

原因是在缺少显式Qualifier批注的情况下,Spring会应用一个后备方法

对于后备匹配,bean名称被认为是默认的限定符值。因此,您可以使用id“ main”而不是嵌套的qualifier元素定义bean,从而得到相同的匹配结果。

不过,依靠变量名显然是一种冒险的方法,如果可能,应避免使用它。如果名称不同步,原本无害的重构可能会完全崩溃。