spring-210724-01--IOC容器--Bean管理XML方式-创建对象和set注入属性

spring-210724-01–IOC容器–Bean管理XML方式-创建对象和set注入属性


IOC操作Bean管理(概念)

1. Bean管理就是指两个操作
	1)Spring创建对象
	2)Spring注入属性
	
2. Bean管理操作
	1)基于xml配置文件方式实现
	2)基于注解方式实现

IOC操作Bean管理(基于xml方式)

1. 基于xml方式创建对象

<!-- 配置User对象创建 -->
<bean id="user" class="com.bgy.spring.User"></bean>

1)在Spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对对象的创建。
2)bean标签对应的属性:
	id:唯一标识
	class:类全路径
	name:和id类似,都是唯一标识,但是这个早期的属性,name属性里面可以有特殊符号。
3)创建对象的时候,默认也是执行无参构造方法完成对象创建。

2. 基于xml方式注入属性

1. DI:依赖注入,就是注入属性(先创建对象,在注入属性)
   两种注入方式:
	1)set方法注入
	2)有参构造注入

IOC和DI的区别:
	DI是IOC中一种具体的实现

set方法注入步骤

第01步:创建类,定义属性和对应的set方法。
第02步:
		<!-- set方法注入属性 -->
        <bean id="book" class="com.bgy.spring.Book">
                <!--
                    使用property完成属性注入
                    name:类里面属性名称
                    value:向属性注入的值
                -->
                <property name="bname" value="数据结构"></property>
                <property name="bauthor" value="严蔚敏"></property>
        </bean>

测试代码:

Book.java

package com.bgy.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;
    }

    public void test(){
        System.out.println(bname+"----"+bauthor);
    }
}

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">
        <!-- set方法注入属性 -->
        <bean id="book" class="com.bgy.spring.Book">
                <!--
                    使用property完成属性注入
                    name:类里面属性名称
                    value:向属性注入的值
                -->
                <property name="bname" value="数据结构"></property>
                <property name="bauthor" value="严蔚敏"></property>
        </bean>
</beans>

TestSpring5.java

import com.bgy.spring.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5 {
    @Test
    public void test_SetInjection() {
         // 1. 加载spring配置文件  bean1.xml
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        
         // 2. 获取配置创建对象
        Book book = context.getBean("book", Book.class);
        
        book.test();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值