Spring框架笔记-IOC容器

3 篇文章 0 订阅
0X0b IOC容器
1、IOC概念和原理
(1)控制和反转,把对象创建和对象之间的调用,交给Spring进行管理
(2)使用IOC的目的:为了耦合度降低

IOC底层原理
XML解析、工厂模式、反射
IOC接口
(1)BeanFactory:IOC容器的基本实现,是Spring内部直接使用,不提供给开发人员使用
	加载配置文件的时候不会创建对象,只有在使用的时候才创建对象
(2)ApplicationContext:BeanFactory的子接口,比BeanFactory功能更强大,提供给开发人员使用
	在加载了配置文件的时候就已经创建了对象
	
	接口有实现类
	FileSystemXmlApplicationContext,后面写的文件路径必须为系统路径
	ClassPathXmlApplicationContext,后面写的文件路径为src下的路径
2、IOC操作Bean管理
什么是Bean管理
	Spring创建对象和Spring注入属性
基于xml的bean管理
1、基于xml方式创建对象
<bean id="user" class="com.company.User"></bean>
(1)在Spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建
(2)在bean标签有很多属性,常用的属性
	* id:唯一标识
	* class:类全路径(包类路径)
(3)创建对象时,默认执行无参数构造方法
基于XML方式注入属性
(1)DI:依赖注入,就是注入属性
	set方法注入或者有参构造注入
(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.company.User">
         使用property完成属性注入
            name:属性的名称
            value:属性的值
    <property name="name" value="hello"></property>
    <property name="password" value="world"></property>
</bean>
    -->

    <!-- 有参构造配置注入属性 -->
    <bean id="user" class="com.company.User">
        <constructor-arg name="name" value="hello"></constructor-arg>
        <constructor-arg name="password" value="world"></constructor-arg>
    </bean>
</beans>
package com.company;

public class User {

    private String name;
    private String password;

//    set方法注入
//    public void setName(String name){
//        this.name = name;
//    }
//
//    public void setPassword(String password){
//        this.password = password;
//    }


    // 有参构造函数
    User(String name, String password){
        this.name = name;
        this.password = password;
    }

    // 测试方法
    public void print() {
        System.out.println(name + ' ' + password);
    }
}
package com.company;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        // 1、加载Spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        // 2、获取配置创建对象,前面是id值
        User user = context.getBean("user", User.class);

        System.out.println(user);
        user.print();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

horizonTel

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值