This tutorial will teach you what @Bean annotation is and how to use it.
The @Bean
annotation indicates that a method produces a bean to be managed by the Spring container. It is a method-level annotation that is used to define beans in Spring configuration files.
How to use @Bean annotation
Here is a simple example of how to use the @Bean
annotation:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
In the example above, the myService
method is annotated with @Bean
and it returns an instance of MyServiceImpl
. This means that the Spring container will manage an instance of MyServiceImpl
and inject it into any dependency that requires it.
Customize the configuration of a bean
You can also use the @Bean
annotation to customize the configuration of a bean. For example:
@Bean @Scope("prototype") public MyService myService() { return new MyServiceImpl(); }
In the example above, the myService
bean is configured to have a “prototype” scope, which means that the Spring container will create a new instance of MyServiceImpl
every time it is requested.
Specify the name of a bean
You can also use the @Bean
annotation to specify the name of a bean, like this:
@Bean(name = "customName") public MyService myService() { return new MyServiceImpl(); }
In this example, the bean is given the name “customName”. This can be useful if you want to reference the bean by a specific name in your code.
I hope this helps! To learn more, check out the Spring Boot tutorials page.