gpt4 book ai didi

java - Spring JavaConfig 如何引用我定义的 bean 来创建新 bean

转载 作者:行者123 更新时间:2023-11-30 03:31:56 24 4
gpt4 key购买 nike

这是我的应用程序 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 创建一个新实例。

最佳答案

实际上它只会创建一个存储库实例。使用s3Repository()在你的@Bean带注释的方法并不真正调用该方法,而只是告诉 spring 将已创建的 bean 类型(如方法的返回类型所暗示的)注入(inject)到 LevelMapperImageDownloader你创建的bean。因此它将在引用该方法的两个 bean 中注入(inject)相同的存储库 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.

关于java - Spring JavaConfig 如何引用我定义的 bean 来创建新 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28819987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com