17
Jul

Create Bean in Setter based with XML

Create Bean in Setter based with XML
======================================

Create entity class "Student.java" in entities package as below:

package entities;

public class Student {

	private String id, name;
	private int age;
	private double score;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

}


Step 2: Create applicationContext.xml file containing Bean definition

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
	<bean id="student1" class="entities.Student">
		<property name="id" value="st101"></property>
		<property name="name" value="Student1"></property>
		<property name="age" value="20"></property>
		<property name="score" value="8.1"></property>
	</bean>
</beans>

Step 3: Client Application

package entities;

import entities.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		try {
			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

			Student student1 = (Student) context.getBean("student1");

			System.out.println("Student data from beans ");

			System.out.println("Id  " + student1.getId());
			System.out.println("Name" + student1.getName());
			System.out.println("Age  " + student1.getAge());
			System.out.println("Score" + student1.getScore());
			
			context.close();

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	}

}


output:

Student data from beans 
Id    st01
Name  Student1
Age   20
Score 8.1

<a href=”http://defectracker.com/wp-content/uploads/2019/07/SpringBeanwithXMLandAnnotationExamples7z.txt”>Sample project for this</a>