沿用上次的工程
新建兩個類
Category和Producthtml
Category.javajava
public class Category { 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; } private int id; private String name="category 1"; }
Product.javaspring
public class Product { private int id; private String name="product 1"; private Category category; 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; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
修改spring-config.xmlthis
<bean name="c" class="com.isdust.zor.pojo.Category"> <property name="name" value="category 1"/> </bean> <bean name="p" class="com.isdust.zor.pojo.Product"> <property name="name" value="product1" /> <property name="category" ref="c"/> </bean>
其中ref用來標記注入,將product注入到category中
執行結果以下:
spa
修改product和category,加入註解,並賦予默認值3d
//爲Product類加上@Component註解,即代表此類是bean @Component("p") public class Product { private int id; private String name="product 1"; @Autowired private Category category; 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; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } } //爲Category 類加上@Component註解,即代表此類是bean @Component("c") public class Category { 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; } private int id; private String name="category 1"; }
修改spring-config.xml,刪除全部子標籤,加入自動掃描code
<context:component-scan base-package="com.isdust.zor.pojo"/> <context:annotation-config/>
執行結果component
結果同xml指定相同xml
致謝
參考資料
官方文檔
http://how2j.cn/k/spring/spri...htm