setter方法注入与内部注入

来源:互联网 发布:王用汲 知乎 编辑:程序博客网 时间:2024/06/16 23:29
1、
package com.itheima.f_xml.b_setter;public class Person {private String pname;private Integer age;private Address homeAddr;//家庭地址private Address companyAddr;//公司地址public String getPname() {return pname;}public void setPname(String pname) {this.pname = pname;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Address getHomeAddr() {return homeAddr;}public void setHomeAddr(Address homeAddr) {this.homeAddr = homeAddr;}public Address getCompanyAddr() {return companyAddr;}public void setCompanyAddr(Address companyAddr) {this.companyAddr = companyAddr;}@Overridepublic String toString() {return "Person [pname=" + pname + ", age=" + age + ", homeAddr=" + homeAddr + ", companyAddr=" + companyAddr + "]";}}


2、

package com.itheima.f_xml.b_setter;public class Address {private String addr;//地址信息private String tel;//电话public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}@Overridepublic String toString() {return "Address [addr=" + addr + ", tel=" + tel + "]";}}

3、beans.xml

<?xml version="1.0" encoding="UTF-8"?><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"><!-- setter方法注入 * 普通数据 <property name="" value="值">等效<property name=""><value>值* 引用数据<property name="" ref="另一个bean">等效<property name=""><ref bean="另一个bean"/>--><bean id="personId" class="com.itheima.f_xml.b_setter.Person"><property name="pname" value="阳志"></property><property name="age"><value>1234</value></property><property name="homeAddr" ref="homeAddrId"></property><property name="companyAddr"><ref bean="companyAddrId"/></property></bean><bean id="homeAddrId" class="com.itheima.f_xml.b_setter.Address"><property name="addr" value="阜南"></property><property name="tel" value="911"></property></bean><bean id="companyAddrId" class="com.itheima.f_xml.b_setter.Address"><property name="addr" value="北京八宝山"></property><property name="tel" value="120"></property></bean></beans>

4、测试

package com.itheima.f_xml.b_setter;import org.junit.Test;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 TestSetter {@Testpublic void demo01(){//从spring容器获得String xmlPath = "com/itheima/f_xml/b_setter/beans.xml";ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);Person person = (Person) applicationContext.getBean("personId");System.out.println(person);}}


原创粉丝点击