We have some beans defined in our ApplicationConfig
like so -
@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);
}
And this is how they are used in code -
public class AssetReader {
@Autowired
private S3Repository s3PrivateContentRepository;
.... used inside the class ....
}
Similarly other beans are named the same as the method that is expected to produce them.
The application works fine but I'm a bit surprised by this, I'm not sure if the bean with the Admin credentials is being autowired everywhere by chance or if the correct beans are being wired in due to some implementation details of Spring?
I thought that it was mandatory to specify a qualifier if Autowiring could produce ambiguous. Assuming that this works as expected, is there any reason for us to qualify these beans?
Spring @Autowired Annotation - Service ClassThe setter method will be used for spring autowiring byName and byType whereas constructor based injection will be used by constructor autowire attribute.
Enabling @Autowired Annotations The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring.
You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.
Autowiring 'byName':This option enables autowire based on bean names. Spring looks up the configuration file for a matching bean name. If found, this bean is injected in the property. However, if no such bean is found, an error is raised.
The reason is that in case of missing explicit Qualifier
annotation Spring applies a fallback method:
For a fallback match, the bean name is considered a default qualifier value. Thus you can define the bean with an id "main" instead of the nested qualifier element, leading to the same matching result.
Still, relying on variable names is cleary a risky approach and you should avoid it if possible. An otherwise harmless refactor can turn into a full meltdown if the names get out of synch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With