|
For the latest stable version, please use Spring Framework 6.2.12! |
Basic Concepts: @Bean and @Configuration
The central artifacts in Spring’s Java configuration support are
@Configuration-annotated classes and @Bean-annotated methods.
The @Bean annotation is used to indicate that a method instantiates, configures, and
initializes a new object to be managed by the Spring IoC container. For those familiar
with Spring’s <beans/> XML configuration, the @Bean annotation plays the same role as
the <bean/> element. You can use @Bean-annotated methods with any Spring
@Component. However, they are most often used with @Configuration beans.
Annotating a class with @Configuration indicates that its primary purpose is as a
source of bean definitions. Furthermore, @Configuration classes let inter-bean
dependencies be defined by calling other @Bean methods in the same class.
The simplest possible @Configuration class reads as follows:
-
Java
-
Kotlin
@Configuration
public class AppConfig {
@Bean
public MyServiceImpl myService() {
return new MyServiceImpl();
}
}
@Configuration
class AppConfig {
@Bean
fun myService(): MyServiceImpl {
return MyServiceImpl()
}
}
The preceding AppConfig class is equivalent to the following Spring <beans/> XML:
<beans>
<bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>
The @Bean and @Configuration annotations are discussed in depth in the following sections.
First, however, we cover the various ways of creating a Spring container by using
Java-based configuration.