مشخصات مقاله
-
529
-
0.0
-
1632
-
0
-
0
آموزش SI Dependent Object-Java Spring
شی وابسته SI
مثال تزریق setter توسط شی وابسته
همانند تزریق سازنده، میتوان با استفاده از setter ها وابستگی bean دیگر را تزریق کرد. در چنین حالتی از عنصر خصیصه استفاده می کنیم. در اینجا سناریو ما Employee HAS-A Address است. شی کلاس آدرس به عنوان شی وابسته در نظر گرفته می شود. در ادامه کلاس آدرس را بررسی می کنیم.
Address.java :
این کلاس شامل چهار خصیصه، setter ، getterو متد toString() است.
package com.javatpoint;
public class Address {
private String addressLine1,city,state,country;
//getters and setters
public String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
Employee.java:
این فایل شامل سه خصیصه شناسه، نام و آدرس(شی وابسته) ، setter و getter به همراه متد displayInfo() است.
package com.javatpoint;
public class Employee {
private int id;
private String name;
private Address address;
//setters and getters
void displayInfo(){
System.out.println(id+" "+name);
System.out.println(address);
}
}
applicationContext.xml :
ویژگی ref از عناصر property برای تعریف مرجع bean دیگری مورد استفاده قرار می گیرد.
< ?xml version="1.0" encoding="UTF-8" ?>
< beans 3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
< bean id="address1" class="com.javatpoint.Address">
< property name="addressLine1" value="51,Lohianagar">< /property>
< property name="city" value="Ghaziabad">< /property>
< property name="state" value="UP">< /property>
< property name="country" value="India">< /property>
< /bean>
< bean id="obj" class="com.javatpoint.Employee">
< property name="id" value="1">< /property>
< property name="name" value="Sachin Yadav">< /property>
< property name="address" ref="address1">< /property>
< /bean>
< /beans>
Test.java:
این کلاس bean را از فایل applicationContext.xml می گیرد و متد displayInfo() را فراخوانی می کند.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e=(Employee)factory.getBean("obj");
e.displayInfo();
}
}