Enjoying this Java & Spring tutorial?
Subscribe to Ram N Java on YouTubeIntroduction
In the Spring Framework, Spring Beans are the backbone of your application. A Spring Bean is simply an object that is instantiated, assembled, and managed by the Spring IoC (Inversion of Control) container.
Instead of manually creating objects using the new keyword, the Spring container takes over the complete lifecycle of beans—from creation and dependency injection to destruction—enabling loose coupling and easy maintenance.
Ways to Define Spring Beans
Spring provides multiple ways to define and configure beans:
- XML Configuration: Defined using the
<bean>tag inside<beans>. - Annotation Configuration: Defined using annotations like
@Component,@Service,@Repository, or@Controller. - Java-Based Configuration: Defined using
@Configurationand@Beanannotations in pure Java classes.
1. Create the Java Bean Class
Here is a simple POJO class named Employee with a name property, setter method, and a display method:
public class Employee {
private String name;
public void setName(String name) {
this.name = name;
}
public void displayEmployeeDetails() {
System.out.println("Employee Name: " + name);
}
}
2. Configure the Bean in Spring XML
In your Spring configuration file (applicationContext.xml), define the bean using the <bean> element, giving it a unique id and configuring its properties:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeBean" class="Employee">
<property name="name" value="Peter" />
</bean>
</beans>
3. Retrieve the Bean from the Spring Container
Load the application context and retrieve the managed bean using its unique ID:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Employee emp = (Employee) context.getBean("employeeBean");
emp.displayEmployeeDetails();
}
}
Watch More Spring Tutorials
Click here to watch on Youtube:
https://www.youtube.com/watch?v=C3iALyO4FJI&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge:
| What are spring beans? | Spring Tutorial | Spring basics | Spring Framework |
| What are spring beans? | Spring Tutorial | Spring basics | Spring Framework |
| What are spring beans? | Spring Tutorial | Spring basics | Spring Framework |
| What are spring beans? | Spring Tutorial | Spring basics | Spring Framework |
