All About Spring Beans

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

Bean Definition

XML configuration

config3.jpg

Using Annotation

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows −

@Configuration
public class BeanConfig {
@Bean
public HelloBean helloBean(){
return new HelloBean();
}
}

Bean Scopes

When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe.

XML Config:

config4.jpg

Annotation Based:

@Configuration
public class BeanConfiguration {

@Bean
@Scope(“prototype”)
public HelloBean helloBean(){
return new HelloBean();
}
}

scopes.jpg

Bean Life Cycle

Please read the Spring Bean Life Cycle.

Leave a Reply

Your email address will not be published. Required fields are marked *