• Spring底层学习 1


    spring两大核心机制:

    IoC:控制反转 / DI:依赖注入

    AOP:面向切面编程

    spring的概述:

    goals:spring因企业级框架过于复杂而诞生,是软件设计层框架 整体管理+项目分层,开发者自主选择组件 解耦合以及高拓展性

    ORM:object relationship mapping

    spring boot spring cloud 都是基于spring

    spring提供各个层面的solution Spring MVC,Spring Data,Spring Cloud

    如何使用IoC: 1.创建Maven工程,添加依赖 spring-context

    2.创建entity类 Student类,包含id,name,age

    传统方式:每次new Student IoC方式:通过配置文件中添加需要管理的对象,XML格式,文件名可以自定义 习惯:XML格式配置文件放在resources包里,java代码放在java包中,不要混

    进入XML: <bean id="student" class="com.james.Student"></bean> id可以自定义

    定义好后需要加载配置文件,利用ApplicationContext类

       ApplicationContext app = new ClassPathXmlApplicationContext("./classpath") Student student = app.getBean("Student")

    同样的可以再Bean中定义属性

    <bean id="student" class="com.james.Student">

      <property name="id" value="12"></property>

      <property name="age" value="11"></property>

      <property name="name" value="aas"></property>

    </bean>

    类似的entity都需要在beans中定义,分别用多个bean标签 bean标签完成对象的管理 id:对象名 class:对象模板类(所有交给IoC容器管理的类必须有无参构造,因为Spring底层通过反射机制创建对象) 对象的成员通过property标签完成赋值 name:成员变量名 value:成员变量值(基本数据类型,String可以直接赋值,如其他引用不能使用value) ref:将IoC中另一个bean赋给当前成员变量(这一过程其实是DI-依赖注入)

    Spring的工厂模式

    Spring取bean的操作其实就是工厂模式的体现

    • 静态工厂模式

    • 实例工厂模式

    我们通过静态工厂类来控制对象的创建,只要读到配置文件,就会将参数传入构造方法并创建,放在IoC容器中,不论我们使用与否。

    Factory类:

    public class Factory {
       private static Map<String,User> userMap;
       static{
           userMap = new HashMap<String,User>();
           userMap.put("James",new User("1L","James"));
      }
       public static User getCar(String username){
           return userMap.get(username);
      }
    }

    Spring-factory.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
         ">

       <bean   id="UserFactory"   class="com.example.factory.Factory" factory-method="getCar">
           <constructor-arg value="James"></constructor-arg>
       </bean>
    </beans>

    FactoryTest测试类:

    public class FactoryTest {
       public static void main(String[] args) {
           ApplicationContext factory = new ClassPathXmlApplicationContext("spring-factory.xml");
           User user =(User) factory.getBean("UserFactory");
           System.out.println(user.getUsername());
           System.out.println(user.getPassword());
      }
    }

    结果是1L,James

    这里注意一下,只要解析到XML后对象已经创建完成,参考单例模式



  • 相关阅读:
    centos 7 和 centoa 8的区别
    centos7制作U盘启动盘
    juypyter notebook安装
    Centos6安装MariaDB
    提job
    report a bug and update
    runtest提交job
    bug
    ps常用选项
    每日一句
  • 原文地址:https://www.cnblogs.com/exigeslover/p/12512757.html
Copyright © 2020-2023  润新知