Spring源码学习(一)---两种容器使用—ApplicationContext和BeanFactory容器

这里主要是使用org.springframework:spring-beans:5.2.0.RELEASE进行分析

  1. Bean是Spring中最重要的部分之一,我们定义一个POJO让它成为Bean

package com.xizi.pojo;

public class Hello {
    private String name;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "Hello{" +
                "name='" + name + '\'' +
                '}';
    }
}

  1. 接下来将类注入配置文件中 将POJO成为Bean注入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">

    <!--bean就是java对象 , 由Spring创建和管理-->
    <bean id="hello" class="com.xizi.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>

</beans>

1. ApplicationContext容器

  1. 测试代码展示
import com.xizi.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    public static void main(String[] args) {
//        获取上下文2对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //对象都在Spring中管理 要使用直接取出来
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello);
    }
}

这里使用ApplicationContext容器

在这里插入图片描述

2. BeanFactory 容器

使用BeanFactory作为容器测试

import com.xizi.pojo.Hello;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class MyTest {

    public static void main(String[] args) {
    
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
        Hello hello = (Hello) beanFactory.getBean("hello");
        System.out.println(hello);
    }
}

结果一致

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值