Basic Concepts: @Bean
and @Configuration
The central artifacts in Infra 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 Infra IoC container. For those familiar
with Infra <beans/>
XML configuration, the @Bean
annotation plays the same role as
the <bean/>
element. You can use @Bean
-annotated methods with any Infra
@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
@Configuration
public class AppConfig {
@Bean
public MyServiceImpl myService() {
return new MyServiceImpl();
}
}
The preceding AppConfig
class is equivalent to the following Infra <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 Infra container by using
Java-based configuration.