IOC操作Bean管理
1、IOC操作Bean管理
a)Bean管理就是两个操作:(1)Spring创建对象 ; (2)Spring注入属性
2、 基于xml配置文件创建对象
1)、Spring配置文件中,使用Bean标签,标签里面添加对应属性,就可以实现对象的创建
2)、在Bean标签中有很多属性,介绍常用的属性
- id属性:唯一标识
- class属性:创建对象所在类的全路径
- name属性:和id属性是一样的,区别:id属性中不能添加特殊符号,class属性中可以添加特殊符号,基本不用了
3)、创建对象时候,默认也是执行无参构造方法
<!--配置User对象的创建-->
<bean id="user" class="com.demo.spring5.User"></bean>
3、基于xml方式注入属性
DL:依赖注入(就是注入属性)
a) set方式注入
public class Book {
private String bname;
private String bauthor;
//创建属性对应的set方法
public void setBname(String bname) {
this.bname = bname;}
public void setBauthor(String bauthor) {
this.bauthor = bauthor; }
public void tesDemo(){
System.out.println(bname+"————————"+bauthor);
}
}
<!-- 1、配置Book对象的创建 2、set方法注入属性 -->
<bean id="book" class="com.demo.spring5.Book">
<!--使用property完成属性注入-->
<property name="bname" value="易筋经"></property>
<property name="bauthor" value="老和尚"></property>
</bean>
public class MainTest {
@Test
public void testadd(){
//1、加载spring的配置文件
ApplicationContext context=
new ClassPathXmlApplicationContext("spring-config.xml");
//2、获取配置创建的对象
Book book = context.getBean("book", Book.class);
System.out.println(book); //com.demo.spring5.Book@42607a4f
book.tesDemo(); //易筋经————————老和尚
}
}
b) 有参构造函数注入
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public void testdemo(){
System.out.println(name+"————————"+age);
}
}
<!--有参构造-->
<bean id="user" class="com.demo.spring5.User">
<constructor-arg name="name" value="阿瑞"></constructor-arg>
<constructor-arg name="age" value="23"></constructor-arg>
</bean>
public class MainTest {
@Test
public void testadduser(){
ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
User user=context.getBean("user",User.class);
System.out.println(user); //com.demo.spring5.User@382db087
user.testdemo(); //阿瑞————————23
}
}
c) p名称空间注入
<!-- 1、配置Book对象的创建 2、set方法注入属性 -->
<bean id="book" class="com.demo.spring5.Book">
<!--使用property完成属性注入-->
<property name="bname" value="易筋经"></property>
<property name="bauthor" value="老和尚"></property>
</bean>
上面这个使用set注入属性的可以简化成下面的
<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" <!--在这添加这个一行,配置完成可以使用p-->
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="book" class="com.demo.spring5.Book" p:bname="九阳神功" p:bauthor="老和尚"></bean>
d)注入空值以及特殊字符
<bean id="book2" class="com.demo.spring5.Book">
<property name="bname" value="奇门遁甲"></property>
<property name="bauthor" value="无名"></property>
<property name="baddress">
<!--<null/> 奇门遁甲————————无名————————null-->
<!--<value>
<![CDATA[<<南京>>]]>
</value> 奇门遁甲————————无名————————<<南京>>-->
<!-- <value><</value> 奇门遁甲————————无名————————< -->
</property>
</bean>