IOC操作(Bean管理)
1、什么是Bean管理
(1)Bean管理的两个操作
(2)Spring创建对象
(3)Spring注入属性
2、Bean管理操作有两种方式
(1)基于xml配置文件方式实现
(2)基于注解方式实现
3、基于xml配置文件方式实现
3.1 基于xml方式创建对象
3.1.1 解释
在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建
3.1.2 在bean标签有很多属性
id属性:唯一标识
class属性:类全路径(包类路径)
3.1.3 创建方法
创建对象时,默认执行无参数构造方法完成对象创建
3.2 基于xml方式注入属性
3.2.1 DI:依赖注入,就是注入属性
(1)第一种注入方式(使用set方法进行注入)
package com.example.spring5.domain;
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;
}
}
在spring配置文件配置对象创建,配置属性注入
<!--2 set方法注入属性-->
<bean id="book" class="com.example.spring5.domain.Book">
<!--使用property完成属性注入
name: 类里面属性名称
value: 向属性注入的值
-->
<property name="bname" value="西瓜"></property>
<property name="bauthor" value="瓜农"></property>
</bean>
测试
package com.example.spring5;
import com.example.spring5.domain.Book;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean1.xml")
class Spring5ApplicationTests {
@Test
public void testAdd(){
//1 加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2 获取配置创建的对象
Book book = context.getBean("book", Book.class);
System.out.println(book);
book.testDemo();
}
}
(2)第二种注入方式(使用有参数构造进行注入)
创建类,定义属性,创建属性对应有参数构造方法
package com.example.spring5.domain;
public class Orders {
//属性
private String oname;
private String address;
//有参数构造
public Orders(String oname, String address) {
this.oname = oname;
this.address = address;
}
}
在spring配置文件中进行配置
<!--3 有参数构造注入属性-->
<bean id="orders" class="com.example.spring5.domain.Orders">
<constructor-arg name="oname" value="abc"></constructor-arg>
<constructor-arg name="address" value="China"></constructor-arg>
</bean>
测试类
package com.example.spring5;
import com.example.spring5.domain.Book;
import com.example.spring5.domain.Orders;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean1.xml")
class Spring5ApplicationTests {
@Test
public void testOrders(){
//1 加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2 获取配置创建的对象
Orders orders = context.getBean("orders", Orders.class);
System.out.println(orders);
orders.ordersTest();
}
}