IOC基于Bean管理(基于xml方式)
1.基于xml方式创建对象
<!--配置User对象创建-->
<bean id-"user" class="com.spring5.User></bean>
(1)在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建
(2)在bean标签有很多属性
- id属性:唯一标识
- class属性:类全路径(包类路径)
(3)创建对象时候,默认也是执行无参构造方法完成对象创建
2.基于xml方法注入属性
(1)DI:依赖注入,注入属性
- 使用set方法注入
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;
}
}
<!--set方法注入属性-->
<bean id="book" class="com.atguigu.spring5.Book">
<!-- 使用property完成属性注入
name:类里面属性名称
value:向属性注入的值
-->
<property name="bname" value="易筋经"></property>
<property name="bauthor" value="达摩老祖"></property>
</bean>
- 使用有参构造进行注入
(1)创建类,定义属性,创建属性对应有参构造方法
public class Orders {
private String oname;
private String address;
public Orders(String oname,String address) {
this.oname = oname;
this.address=address;
}
}
(2)在spring配置文件中进行配置
<!--有参构造注入属性-->
<bean id="orders" class="com.atguigu.spring5.Orders">
<constructor-arg name="oname" value="电脑"></constructor-arg>
<constructor-arg name="address" value="China"></constructor-arg>
</bean>
- p名称空间注入
(1)使用p名称空间注入,可以简化基于xml配置方式
- 添加p名称空间在配置文件中
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- 进行属性注入,在bean标签里面进行操作
<bean id="book" class="com.atguigu.spring5.Book" p:bname="九阳神功" p:bauthor="无名氏">
</bean>
IOC操作Bean管理(xml注入其他类型属性)
1.字面量
(1)null值
<!--null值-->
<property name="address">
<null/>
</property>
(2)属性值包含特殊符号
<!--属性值包含特殊符号
1.进行转义 <>
2.把特殊符号内容写到CDATA
-->
<property name="address" >
<value>
<![CDATA[<<南京>>]]>
</value>
</property>
IOC操作Bean管理(xml注入集合类型属性)
1.注入数组类型属性
2.注入list集合类型属性
3.注入map集合类型属性
(1)创建类,定义数组,list,map,set类型属性,生成对应set方法。
public class Stu {
private String[] courses;
private List<String> list;
private Map<String,String> maps;
private Set<String> sets;
public void setCourses(String[] courses) {
this.courses = courses;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public void setSets(Set<String> sets) {
this.sets = sets;
}
}
(2)在spring配置文件中进行配置
<!--集合类型属性注入-->
<bean id="stu" class="com.atguigu.spring5.Stu">
<!--数组类型属性注入-->
<property name="courses">
<array>
<value>java课程</value>
<value>数据库课程</value>
</array>
</property>
<!--list类型属性注入-->
<property name="list">
<list>
<value>张三</value>
<value>小明</value>
</list>
</property>
<!--map类型属性注入-->
<property name="maps">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="PHP" value="php"></entry>
</map>
</property>
<!--set类型属性注入-->
<property name="sets">
<set>
<value>MySQL</value>
<value>Redis</value>
</set>
</property>
</bean>
以上为尚硅谷视频学习笔记。