简体   繁体   English

Spring JavaConfig我如何引用为创建新bean而定义的bean

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

Here's an excerpt from my Applications beans definition, I want to be able to refer to beans that I have defined. 这是我的Applications 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()); }
}

Right now what I'm doing is calling methods like s3Repository() in two places; 现在我正在做的是在两个地方调用s3Repository()类的方法。 this way I'll be creating two instances of the repository whereas I would like there to be only one instance across the application. 这样,我将创建存储库的两个实例,而我希望整个应用程序中只有一个实例。 Something like credentialsProvider() is lightweight so I don't mind a new instance being created for every bean. 诸如credentialsProvider()类的东西很轻巧,因此我不介意为每个bean创建一个新实例。

Actually it will only create one instance of repository. 实际上,它只会创建一个存储库实例。 Using s3Repository() in your @Bean annotated method doesn't really call that method, but just tells the spring to inject the already created bean of type (as implied by return type of method) to the LevelMapper and ImageDownloader bean you create. @Bean注释的方法中使用s3Repository()并不会真正调用该方法,而只是告诉Spring将已经创建的类型(如方法的返回类型所暗示)的bean注入到您创建的LevelMapperImageDownloader bean中。 So it will inject the same repository bean instance in both the beans referencing the method. 因此,它将在引用该方法的两个bean中注入相同的存储库bean实例。

From this Spring Docs : 从这个春季文件

All @Configuration classes are subclassed at startup-time with CGLIB. 所有@Configuration类在启动时都使用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. 在子类中,子方法在调用父方法并创建新实例之前,首先检查容器中是否有任何缓存(作用域)的bean。 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. 请注意,从Spring 3.2开始,不再需要将CGLIB添加到您的类路径中,因为CGLIB类已经在org.springframework下重新打包并直接包含在spring-core JAR中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM