A Bean is a POJO(Plain Old Java Object), which is managed by the spring container.
Spring containers create only one instance of the bean by default. ?This bean it is cached in memory so all requests for the bean will return a shared reference to the same bean.
The @Bean annotation returns an object that spring registers as a bean in application context.?The logic inside the method is responsible for creating the instance.
When do we use @Bean annotation?
When automatic configuration is not an option. For example when we want to wire components from a third party library, because the source code is not available so we cannot annotate the classes with @Component.
A Real time scenario could be that someone wants to connect to Amazon S3 bucket. Because the source is not available he would have to create a @bean.
@Bean
public AmazonS3 awsS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsKeyId, accessKey);
return AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(region))
.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
}
Source for the code above -> https://www.devglan.com/spring-mvc/aws-s3-java
Because I mentioned @Component Annotation above.
@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and class path scanning.
Component annotation registers the class as a single bean.