Spring JavaConfig 如何引用我定义的 beans 来创建新的 beans

Spring JavaConfig how do I refer to beans that I have defined to create new beans

这是我的应用程序 bean 定义的摘录,我希望能够引用我定义的 bean。

@Configuration
@ComponentScan({"com.abc.config", "com.abc.config.common"})
public class ApplicationConfig {
    @Bean(name = "AWSCredentialsProvider")
    AWSCredentials credentialsProvider() { return new AWSCredentials(/*Omitted*/); }  
    @Bean(name = "DynamoDBClient")
    AmazonDynamoDBClient dynamoDBClient() {
        AmazonDynamoDBClient dynamoDB = new AmazonDynamoDBClient(credentialsProvider());
        return dynamoDB;        
    }  
    @Bean S3Repository s3Repository() {
        AmazonS3 s3 = new AmazonS3Client(credentialsProvider());
        return new S3Repository(s3);
    }  
    @Bean LevelMapper levelMapper() { return new LevelMapper(s3Repository()); }
    @Bean ImageDownloader imageDownloader() { return new ImageDownloader(s3Repository()); }
}

现在我正在做的是在两个地方调用像 s3Repository() 这样的方法;这样我将创建存储库的两个实例,而我希望整个应用程序只有一个实例。 credentialsProvider() 之类的东西是轻量级的,所以我不介意为每个 bean 创建一个新实例。

实际上它只会创建一个存储库实例。在你的 @Bean 注释方法中使用 s3Repository() 并没有真正调用该方法,只是告诉 spring 注入已经创建的类型的 bean(如 return 类型所暗示的方法)到您创建的 LevelMapperImageDownloader bean。因此它将在引用该方法的两个 bean 中注入相同的存储库 bean 实例。

从这个Spring Docs:

All @Configuration classes are subclassed at startup-time with CGLIB. In the subclass, the child method checks the container first for any cached (scoped) beans before it calls the parent method and creates a new instance. Note that as of Spring 3.2, it is no longer necessary to add CGLIB to your classpath because CGLIB classes have been repackaged under org.springframework and included directly within the spring-core JAR.