Bean管理指的是:
(1)Spring 创建对象
(2)Spring 注入属性
基于XML方式创建对象,并且注入属性(SET方式):
1.定义一个类,并且定义俩属性,创建对应set方法:
public class Book {
private String name;
private String auther;
public void setName(String name) {
this.name = name;
}
public void setAuther(String auther) {
this.auther = auther;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + ''' +
", auther='" + auther + ''' +
'}';
}
}
2.在src路径下写XML配置文件
3.创建测试类
public class testBook {
@Test
public void testDemo(){
1 加载 spring 配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
// 2 获取配置创建的对象
Book book = context.getBean("book", Book.class);
System.out.println(book.toString());
}
}
注:
ApplicationContext加载配置文件时候就会吧在配置文件的对象进行创建,俗称饿汉式,利用空间换时间。
ApplicationContext接口有如下实现类:
—ClassPathXmlApplicationContext写的是在src下的路径
—FileSystemXmlApplicationContext写的是在磁盘中的路径
结果:



