Spring_IOC容器:注入属性的两种方式(Bean管理)
IOC操作 -Bean管理
1.什么事Bean管理
Bean管理指的两个属性:
- 由spring创建对象
- spring注入属性
2.Bean管理的两种操作方式
- 基于xml配置文件方式实现
- 基于注解方式实现
IOC操作Bean管理(基于XML)
1.基于xml方式创建对象
(1).在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象的创建
上节课入门案例中,xml文件:
<!--配置User对象创建-->
<bean id="user" class="com.tinstu.spring.User"></bean>
(2)bean标签中有很多属性,介绍常用的属性
- id :非对象名,是对象名的唯一标识
- class:类全路径(包类路径)
(3)创建对象的时候,默认也是执行无参数构造方法完成对象创建
2.基于xml方式注入属性
DI:依赖注入,就是注入属性
第一种注入方式:使用set方式进行注入
book.java
package com.tinstu.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;
}
}
在spring配置文件配置对象创建,配置属性注入 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"> <!--2.set方法注入属性--> <bean id="book" class="com.tinstu.spring.Book"> <!--使用property完成属性注入--> <property name="bname" value="123"></property> <property name="bauthor" value="456"></property> </bean> </beans>
第二种注入方式:通过有参数的构造进行注入
(1)创建类,定义属性,创建属性对应有参数构造方法
package com.tinstu.spring;
public class Book {
private String bname;
private String bauthor;
public Book(String bname, String bauthor) {
this.bname = bname;
this.bauthor = bauthor;
}
}
(2).在spring文件中进行配置
<?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.tinstu.spring.Book">
<constructor-arg name="bname" value="apple"></constructor-arg>
<constructor-arg name="bauthor" value="fubusi"></constructor-arg>
<!-- 或者用index<constructor-arg index=“0” value="fubusi"></constructor-arg>-->
</bean>
</beans>
了解:p名称空间注入:
(1)使用p空间注入,可以简化基于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"
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">
(2)进行属性注入,在bean标签里面进行操作
<bean id="user" class="com.tinstu.spring.User" p:bname="九阳神功" p:bauthor="无名氏"></bean>
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/1001.html
文章版权归作者所有,未经允许请勿转载。
THE END