spring-210724-01–IOC容器–Bean管理XML方式-创建对象和set注入属性
IOC操作Bean管理(概念)
1. Bean管理就是指两个操作
1)Spring创建对象
2)Spring注入属性
2. Bean管理操作
1)基于xml配置文件方式实现
2)基于注解方式实现
IOC操作Bean管理(基于xml方式)
1. 基于xml方式创建对象
<!-- 配置User对象创建 -->
<bean id="user" class="com.bgy.spring.User"></bean>
1)在Spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对对象的创建。
2)bean标签对应的属性:
id:唯一标识
class:类全路径
name:和id类似,都是唯一标识,但是这个早期的属性,name属性里面可以有特殊符号。
3)创建对象的时候,默认也是执行无参构造方法完成对象创建。
2. 基于xml方式注入属性
1. DI:依赖注入,就是注入属性(先创建对象,在注入属性)
两种注入方式:
1)set方法注入
2)有参构造注入
IOC和DI的区别:
DI是IOC中一种具体的实现
set方法注入步骤
第01步:创建类,定义属性和对应的set方法。
第02步:
<!-- set方法注入属性 -->
<bean id="book" class="com.bgy.spring.Book">
<!--
使用property完成属性注入
name:类里面属性名称
value:向属性注入的值
-->
<property name="bname" value="数据结构"></property>
<property name="bauthor" value="严蔚敏"></property>
</bean>
测试代码:
Book.java
package com.bgy.spring;
public class Book {
private String bname;
private String bauthor;
public void setBname(String bname) {
this.bname = bname;
}
public void setBauthor(String bauthor) {
this.bauthor = bauthor;
}
public void test(){
System.out.println(bname+"----"+bauthor);
}
}
bean1.xml
<?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="book" class="com.bgy.spring.Book">
<property name="bname" value="数据结构"></property>
<property name="bauthor" value="严蔚敏"></property>
</bean>
</beans>
TestSpring5.java
import com.bgy.spring.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring5 {
@Test
public void test_SetInjection() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Book book = context.getBean("book", Book.class);
book.test();
}
}