• Spring 容器的基本用法


    容器的基本用法

    bean 是 Spring 中最核心的东西,因为 Spring 就像是个大水桶,而 bean 就像是容器中的水,水桶脱离了水也没什么用处了,来看看 bean 的定义。

    public class MyTestBean {
    
        private String testStr = "testStr";
    
        public String getTestStr() {
            return testStr;
        }
    
        public void setTestStr(String testStr) {
            this.testStr = testStr;
        }
    }

    Spring 的目的就是让 bean 成为一个纯粹的 POJO ,这是 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"
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
    
        <bean id="myTestBean" class="com.zhen.bean.test.MyTestBean"/>
        
    </beans>

    测试代码

    public class BeanFactoryTest {
        public static void main(String[] args) {
            @SuppressWarnings("deprecation")
            BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beanFactoryTest.xml"));
            MyTestBean bean = (MyTestBean) beanFactory.getBean("myTestBean");
            System.out.println(bean.getTestStr());
        }
    }

    直接使用 BeanFactory 作为容器对于 Spring 的使用来说并不多见,甚至是极少使用,因为在企业级的应用中大多数都会使用的是 ApplicationContext,这里知识用于测试,可以更好的分析 Spring的内部原理。

    功能分析

      上边这段测试代码完成的功能:

    1. 读取配置文件 beanFactoryTest.xml
    2. 根据 beanFactoryTest.xml 中的配置找到对应的类的配置,并实例化。
    3. 调用实例化后的实例

    • ConfigReader : 用于读取及验证配置文件。我们要用配置文件里边的东西,当然首先要做的就是读取,然后放置在内存中。
    • ReflectionUtil : 用于根据配置文件中的配置进行反射实例化。例如上边例子中的 
      <bean id="myTestBean" class="com.zhen.bean.test.MyTestBean"/>,我们可以根据com.zhen.bean.test.MyTestBean进行实例化。
    • App : 用于完成整个逻辑的串联。
  • 相关阅读:
    Intel x86
    FPGA自计数六位共阳极数码管动态显示2(调用task的方法)
    FPGA六位共阳极数码管动态显示
    运算放大器是模拟电路的基石,模拟电路设计
    这样讲你就懂了!大牛给你介绍《信号与系统》
    电容计算公式
    fork...join的用法
    芯片电源管脚的去耦电容究竟要用多大的?
    Blog Contents
    linux grep 命令常见用法
  • 原文地址:https://www.cnblogs.com/EnzoDin/p/6572378.html
Copyright © 2020-2023  润新知