In Spring Framework, a bean is an object that is managed by the Spring IoC container. It is simply a Java object that is instantiated, assembled, and otherwise managed by Spring Framework’s IoC container. Essentially, the bean is the fundamental building block of any Spring-based application.
Beans are defined in the Spring Framework using Java configuration or XML-based configuration. Java configuration involves the use of Java classes annotated with ‘@Configuration‘ and ‘@Bean‘ annotations, while XML configuration involves the use of a Spring XML configuration file to define beans.
Here is an example of defining a bean using Java configuration:
@Configuration
public class MyConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
In this example, ‘MyBean‘ is a simple Java class, and the ‘myBean‘ method is annotated with ‘@Bean‘, which tells Spring that this method returns a bean object that should be managed by the container.
Here is an example of defining beans using XML configuration:
<beans>
<bean id="myBean" class="com.example.MyBean"/>
</beans>
In this example, the ‘id‘ attribute identifies the name of the bean, and the ‘class‘ attribute specifies the fully-qualified class name of the bean that will be instantiated.
Once a bean is defined, it can be accessed by other beans in the same container or by application code that uses the container. During runtime, the Spring IoC container is responsible for creating instances of beans, managing their lifecycle, and providing them to other parts of the application as needed.