1.创建一个项目,导入jar包(ioc)
2.拷贝applicationContext.xml到src下
3.创建一个bean包,类分别是Book和CartItem,分别提供get,set方法,toStrong和有参,无参
4.在applicationContext.xml进行配置bean,然后进行级联属性赋值
5.进行测试
--------------------------------------------------------------------------------------------------------------------
bean
1 package com.xcz.bean; 2 3 public class Book { 4 private int id; 5 private String name; 6 private int price; 7 public Book() { 8 super(); 9 }10 public Book(int id, String name, int price) {11 super();12 this.id = id;13 this.name = name;14 this.price = price;15 }16 public int getId() {17 return id;18 }19 public void setId(int id) {20 this.id = id;21 }22 public String getName() {23 return name;24 }25 public void setName(String name) {26 this.name = name;27 }28 public int getPrice() {29 return price;30 }31 public void setPrice(int price) {32 this.price = price;33 }34 @Override35 public String toString() {36 return "Book [id=" + id + ", name=" + name + ", price=" + price + "]\n";37 }38 39 }
1 package com.xcz.bean; 2 3 public class CartItem { 4 private Book book; 5 private String count; 6 private double amount; 7 8 public CartItem() { 9 super();10 }11 public CartItem(Book book, String count, double amount) {12 super();13 this.book = book;14 this.count = count;15 this.amount = amount;16 }17 public Book getBook() {18 return book;19 }20 public void setBook(Book book) {21 this.book = book;22 }23 public String getCount() {24 return count;25 }26 public void setCount(String count) {27 this.count = count;28 }29 public double getAmount() {30 return amount;31 }32 public void setAmount(double amount) {33 this.amount = amount;34 }35 @Override36 public String toString() {37 return "CartItem [book=" + book + ", count=" + count + ", amount=" + amount + "]\n";38 }39 40 }
applicationContext.xml
1 222 23 24 28 2925 26 27 30 3731 32 33 34 35 36
test
1 package com.xcz.bean.test; 2 3 4 import org.junit.jupiter.api.Test; 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7 8 import com.xcz.bean.CartItem; 9 10 class CarItemTest {11 //创建IOC容器12 ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");13 @Test14 void test1() {15 CartItem cItem = (CartItem) ioc.getBean("carItem");16 System.out.println(cItem);17 }18 }