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配置文件
<!-- 配置User对象创建
id:给对象起个别名,通过名字来得到对象(唯一的标识)
class:类全路径 (包类路径)
-->
<bean id="book" class="Day1024.Book">
<!-- set方法注入属性(要写道bean标签内)-->
<!--使用property完成属性注入
name:类里面属性名称
value:向属性注入的值
-->
<property name="name" value="人间失格"></property>
<property name="auther" value="太宰治"></property>
</bean>
<!--以上操作就完成了一个注入-->
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写的是在磁盘中的路径
结果: