Spring Autowire是否通过Java Config的方法名称进行自动装配

时间:2016-01-11 18:57:25

标签: 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);
}

这就是它们在代码中的使用方式 -

public class AssetReader {
@Autowired
private S3Repository s3PrivateContentRepository;
.... used inside the class ....
}

类似地,其他bean的命名方式与预期生成它们的方法相同。

该应用程序工作正常,但我对此感到惊讶,我不确定具有管理员凭据的bean是否偶然在所有地方自动装配,或者是否由于某些正在连接正确的bean Spring的实现细节?

我认为如果自动装配可能产生歧义,则必须指定限定符。假设这是按预期工作的,我们是否有理由对这些bean进行限定?

1 个答案:

答案 0 :(得分:5)

原因是如果缺少明确的Qualifier注释,Spring会应用fallback method

  

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

尽管如此,依靠变量名称是一种危险的方法,如果可能的话你应该避免使用它。如果名称不同步,那么无害的重构可能会变成完全崩溃。