18
Jul

Create Bean in Constructor Based with XML

Create Bean in Constructor Based with XML

Step 1: Create Student.java in entitites package
=================================================

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: Configuration file:
=============================
Create applicationContextConstructor.xml file containing Beans 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">
		<constructor-arg value="st101"></constructor-arg>
		<constructor-arg value="Student1"></constructor-arg>
		<constructor-arg value="20"></constructor-arg>
		<constructor-arg value="8.1"></constructor-arg>
	</bean>
</beans>



Step 3: Client application
===========================

package entities;

import entities.Student;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import annotations.StudentConfig;

public class MainConstructorXML {

	public static void main(String[] args) {
		try {
			AbstractApplicationContext context = new AnnotationConfigApplicationContext(StudentConfig.class);

			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
Namestudent1
Age  20
Score8.9