Using the @Bean annotation
- You have full control over the instance creation you add to the Spring context. It is your responsibility to create and configure the instance in the body of the method annotated with @Bean. Spring only takes that instance and adds it to the context as-is.
- You can use this method to add more instances of the same type to the Spring context.
- You can use the @Bean annotation to add to the Spring context any object instance. The class that defines the instance doesn’t need to be defined in your app. A String and an Integer to the Spring context.
- You need to write a separate method for each bean you create, which adds boilerplate code to your app. For this reason, we prefer using @Bean as a second option to stereotype annotations in our projects.
Using stereotype annotations
- You only have control over the instance after the framework creates it.
- This way, you can only add one instance of the class to the context.
- You can use stereotype annotations only to create beans of the classes your application owns. For example, you couldn’t add a bean of type String or Integer as like with the @Bean annotation because you don’t own these classes to change them by adding a stereotype annotation.
- Using stereotype annotations to add beans to the Spring context doesn’t add boilerplate code to your app. You’ll prefer this approach in general for the classes that belong to your app.