1、什么是Bean管理
(0)Bean管理指的是两个操作
(1) Spring创建对象
(2) Spirng注入属性
2、Bean管理操作有两种方式
(1)基于xml配置文件方式实现
(2)基于注解方式实现
IOC操作Bean管理(基于xml方式)
1、基于xml方式创建对象
<!--配置user对象创建--> <bean id="user" class="com.gsafety.spring5.User"></bean>
(1)在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建
(2)在bean标签有很多属性,介绍常用的属性
*id属性:唯一标识
*class属性:类全路径(包类路径)
(3)创建对象时候,默认也是执行无参数构造方法完成对象创建
2、基于xml方式注入属性
(1)DI:依赖注入,就是注入属性
3、第一种注入方式:使用set方法进行注入
(1)创建类,定义属性和对应的set方法
public class Book { private String bname; private String bautor; public void setBname(String bname) { this.bname = bname; } public void setBautor(String bautor) { this.bautor = bautor; } public void testDemo(){ System.out.println("testDemo......"); } @Override public String toString() { return "Book{" + "bname='" + bname + '\'' + ", bautor='" + bautor + '\'' + '}'; } }
(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"> <!--配置user对象创建--> <bean id="user" class="com.gsafety.spring5.User"></bean> <!--set注入属性--> <bean id="book" class="com.gsafety.spring5.Book"> <property name="bautor" value="金庸"></property> <property name="bname" value="天龙八部"></property> </bean> </beans>
测试类: public class TestSpring5 { @Test public void testAdd(){ //1、加载spring配置文件 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean1.xml"); //2、获取配置创建的对象 User user = applicationContext.getBean("user", User.class); System.out.println(user); user.add(); } @Test public void testDemo(){ //1、加载spring配置文件 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean1.xml"); //2、获取配置创建的对象 Book book = applicationContext.getBean("book", Book.class); System.out.println(book); book.testDemo(); } } 输出: Book{bname='天龙八部', bautor='金庸'} testDemo......
本文含有隐藏内容,请 开通VIP 后查看