對Category和Product注入屬性,並且對Product對象,注入一個Category對象
一、新建項目
二、導包
三、新建Category類
package com.yyt.pojo; public class Category { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
四、新建Product類,將添加一個Category類型屬性
package com.yyt.pojo; public class Product { private int id; private String name; private float price; private Category category;
五、在src目錄下新建applicationContext.xml文件
要注入對象,需在property中添加ref=“該類在bean中的name”,例如本次的 “c”是Category在bean中的name值
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean name="c" class="com.yyt.pojo.Category"> <property name="id" value="1" /> <property name="name" value="category 1" /> </bean> <bean name="p" class="com.yyt.pojo.Product"> <property name="id" value="1" /> <property name="name" value="product 1" /> <property name="price" value="8848" /> <property name="category" ref="c" /> </bean> </beans>
六、Test類
package com.yyt.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yyt.pojo.Category; import com.yyt.pojo.Product; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml"}); Category cg = (Category) context.getBean("c"); System.out.println("id:"+cg.getId()+" name:"+cg.getName()); Product p = (Product) context.getBean("p"); System.out.println("id:"+p.getId()+" name:"+p.getName()+" price:"+p.getPrice()); //輸出注入的對象 System.out.println(p.getCategory().getName()); } }
注:基於框架的程序要成功運行,對於JAR包的版本,配置文件的正確性有着苛刻的要求,任何一個地方出錯了,都會導致框架程序運行失敗。
該項目上傳了GitHub:https://github.com/yeyangtao/Spring