①创建IOC容器对象
package com.ioc.bean;
public class Book {
private Integer BookId;
private String BookName;
private String author;
private double price;
public Book() {System.out.println("构造器已经创建");}
public Book(Integer bookId, String bookName, String author, double price) {
super();
BookId = bookId;
BookName = bookName;
this.author = author;
this.price = price;
}
public Integer getBookId() {
return BookId;
}
public void setBookId(Integer bookId) {
BookId = bookId;
}
public String getBookName() {
return BookName;
}
public void setBookName(String bookName) {
BookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [BookId=" + BookId + ", BookName=" + BookName + ", author=" + author + ", price=" + price + "]";
}
}
ApplicationContext接口
package com.ioc.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class IOCTest {
@Test
public void test() {
ApplicationContext myIoc = new ClassPathXmlApplicationContext("j.xml");
System.out.println("ioc已经创建");
Object bean = myIoc.getBean("book01");
System.out.println(bean);
}
}
②调用IOC容器对象的getBean()方法即可获取IOC容器中配置的bean对应的对象
[1]getBean(String id) 根据配置文件中指定的bean的id获取
[2]getBean(Class<?> clazz) 根据bean的类型
根据类型获取bean的前提条件是IOC容器中指定类型的bean只有一个
<?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">
<bean id="book01" class="com.ioc.bean.Book">
<property name="bookId" value="1"></property>
<property name="bookName" value="bookName01"></property>
<property name="author" value="author01"></property>
<property name="price" value="100"/>
</bean>
</beans>