zoukankan      html  css  js  c++  java
  • Spring入门01

    一、Spring简单案例

    1、搭建Spring基本项目

    https://repo.spring.io/webapp/#/artifacts/browse/tree/General/libs-release-local/org/springframework/spring/5.1.3.RELEASE/spring-framework-5.1.3.RELEASE-dist.zip

    导入基本jar包:context  core  beans  expression

    与apache的logging,老版本还需要导入log4j

    创建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对象交给Spring管理 -->
        <!-- Bean元素:使用该元素描述需要Spring容器管理的对象 
                class属性:被管理对象的完整类名
                name属性:给被管理的对象起名字,获得对象时根据该名称获得对象,名称可以重复,可以使用特殊字符
                id:与name属性一模一样(名称不可重复,不能使用特殊字符)
            结论:尽量使用name属性
        -->
        <bean name="user" class="domain.User"></bean>
    
    </beans>

    配置查找约束:spring-framework-4.2.4.RELEASEdocsspring-framework-referencehtmlxsd-configuration.html

    创建测试案例

    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import domain.User;
    
    public class Demo1 {
    
        /**
         * IOC:Inverse of Control 反转控制
         *     将我们创建对象的方式反转了
         *     以前对象的创建是由我们开发人员自己维护,包括依赖关系也是自己注入
         *     使用了spring之后,对象创建以及依赖关系可以由spring完成创建以及注入
         *     反转控制就是反转了对象的创建方式,从我们自己创建反转给了程序(spring)
         * 
         * DI:Dependency Injection  依赖注入
         * 实现IOC思想需要DI做支持
         * 注入方式:set方法注入
         *           构造方法注入
         *          字段注入
         * 注入类型:
         *         值类型注入   8大基本数据类型
         *         引用类型注入   将依赖的对象注入
         * 
         * ApplicationContext&BeanFactory(过时)
         * 
         *     BeanFactory接口:spring原始接口,针对原始接口实现类功能较为单一
         *  BeanFactory接口实现类的容器:每次在获得对象时才会创建对象
         *  
         *  ApplicationContext
         *      每次容器启动时就会创建容器中配置的所有对象,提供更多功能
         *      web开发中使用ApplicationContext完成
         *      在资源匮乏的环境可以使用BeanFactory
         *  从类路径下加载配置文件:ClassPathXmlApplicationContext
         *  从硬盘绝对路径下加载配置文件:FileSystemXmlApplicationContext("d:/xx.xx")
         * */
        @Test
        public void func1() 
        {
        
            //1、创建容器对象
            ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            //2、向容器要user
            User user = (User) context.getBean("user");
            //打印一下User
            System.out.println(user);
        }
        
        @Test
        public void func2() {
            
            
        }
    }

     2、Bean元素进阶配置

    scpoe属性:

        singleton(默认值):单例对象,被标识为单例的对象在spring容器中只存在一个实例

        prototype:多例原型,被标识为多例的对象,每次在获得才会创建。每次创建都是新的对象。

        request:web环境下,对象与request生命周期一致

        session:web环境下,对象与session生命周期一致

     <bean name="user" class="domain.User" scope="prototype"></bean>
     <bean name="user" class="domain.User" scope="singleton"></bean>

    生命周期属性:

        init-method 初始化方法:配置一个方法作为对象生命周期初始化方法,spring会在对象创建后立即调用

        destory-method 销毁方法:配置一个方法作为生命周期的销毁方法,spring容器在关闭并销毁所有容器中的对象之前调用

    <bean name="user" class="domain.User" init-method="init" destroy-method="destory"></bean>

    3、spring创建对象的方式

    方式一、

      空参构造(主要方式)

    <!-- 创建方式1:空参构造创建   (主要方式) -->
        <bean name="user" class="domain.User"></bean>

    方式二、静态工厂

    public class UserFactory {
    
        public static User Create() {
            
            System.out.println("静态工厂方式");
            return new User();
        }
    }
        <!-- 创建方式2:静态工厂创建
            调用UserFactory的Create方法创建user2对象,放入容器
         -->
         <bean name="user2" class="domain.UserFactory" factory-method="Create"></bean>

    方式三、实例工厂

    public User Create2() {
            
            System.out.println("实例工厂工厂方式");
            return new User();
        }
    <!-- 方式3:实例工厂
            调用UserFactory对象的Create2方法创建名为user3的对象,放入容器
         -->
         <bean name="user3" factory-bean="userFactory" factory-method="Create2"></bean>
         
         <bean name="userFactory" class="domain.UserFactory"></bean>

    Spring的分模块配置

    <!-- 导入其他配置文件 -->
        <import resource="CreateObjDemo/applicationContext.xml"/>

    3、spring的属性注入

    一、set方式注入

    <!-- set注入方式 -->
        <bean name="user" class="domain.User">
            <!-- 值类型注入 -->
            <property name="name" value="zhangsan"></property>
            <property name="age" value="20"></property>
            <!-- 引用类型注入,注入的是下面配置的car对象 -->
            <property name="Mycar" ref="car"></property>
            
        </bean>
        
        <!-- car对象 -->
        <bean name="car" class="domain.Car">
            <property name="name" value="兰博基尼"></property>
            <property name="color" value="红色"></property>
        </bean>

    二、构造函数注入

        <!--构造函数注入  -->
        <bean name="user2" class="domain.User">
            <!-- 
            name属性:构造函数的参数名
            index属性:构造函数的参数索引
            type属性:构造函数的参数类型
             -->
            <constructor-arg name="name" index="0" type="java.lang.String" value="李四"></constructor-arg>
            <constructor-arg name="age" index="1" type="java.lang.Integer" value="25"></constructor-arg>
            <constructor-arg name="car" index="2" ref="car"></constructor-arg>
        </bean>

    三、p名称空间注入

    <!-- p名称空间,走set方法
            1、导入p名称空间  xmlns:p="http://www.springframework.org/schema/p"
            2、使用p:属性完成注入
         -->
         <bean name="user3" class="domain.User" p:name="王五" p:age="22" p:Mycar-ref="car"></bean>

     四、spel注入

     <!-- spel注入:Spring Expression Language (Spring表达式语言) -->
         <bean name="user4" class="domain.User">
             <property name="name" value="#{user.name}"></property>
             <property name="age" value="#{user.age}"></property>
             <property name="Mycar" ref="car"></property>
         </bean>

    五、复杂类型注入(array、list、map、Properties)

    <!-- 复杂类型注入 -->
            <bean name="lmp" class="domain.Lmp">
                <!--Array数组注入 -->
                <property name="arr">            
                    <array>
                        <value>tom</value>
                        <value>jack</value>
                        <ref bean="user2"/>
                    </array>            
                </property>
                <!-- list集合注入 -->
                <property name="list">            
                    <list>
                        <value>zhangsan</value>
                        <value>lisi</value>
                        <ref bean="user3"/>
                    </list>
                </property>
                <!-- map集合注入 -->
                <property name="map">
                    <map>                    
                        <entry key="school" value="清华"></entry>
                        <entry key-ref="user" value-ref="car"></entry>
                    </map>
                </property>
                <!-- Properties类型注入 -->
                <property name="pro">
                    <props>
                        <prop key="school">北大</prop>
                        <prop key="name">张三</prop>
                    </props>
                </property>
            </bean>
    public class Lmp 
    {
        private Object arr[];
        private List list;
        private Map map;
        private Properties pro;
        public Object[] getArr() {
            return arr;
        }
        public void setArr(Object[] arr) {
            this.arr = arr;
        }
        public List getList() {
            return list;
        }
        public void setList(List list) {
            this.list = list;
        }
        public Map getMap() {
            return map;
        }
        public void setMap(Map map) {
            this.map = map;
        }
        public Properties getPro() {
            return pro;
        }
        public void setPro(Properties pro) {
            this.pro = pro;
        }
        @Override
        public String toString() {
            return "Lmp [arr=" + Arrays.toString(arr) + ", list=" + list + ", map=" + map + ", pro=" + pro + "]";
        }
    }

    一二三四五案例全部配置

    <?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:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
            
        <!-- set注入方式 -->
        <bean name="user" class="domain.User">
            <!-- 值类型注入 -->
            <property name="name" value="zhangsan"></property>
            <property name="age" value="20"></property>
            <!-- 引用类型注入,注入的是下面配置的car对象 -->
            <property name="Mycar" ref="car"></property>
            
        </bean>
    
        
        <!-- car对象 -->
        <bean name="car" class="domain.Car">
            <property name="name" value="兰博基尼"></property>
            <property name="color" value="红色"></property>
        </bean>
    
        <!--构造函数注入  -->
        <bean name="user2" class="domain.User">
            <!-- 
            name属性:构造函数的参数名
            index属性:构造函数的参数索引
            type属性:构造函数的参数类型
             -->
            <constructor-arg name="name" index="0" type="java.lang.String" value="李四"></constructor-arg>
            <constructor-arg name="age" index="1" type="java.lang.Integer" value="25"></constructor-arg>
            <constructor-arg name="car" index="2" ref="car"></constructor-arg>
        </bean>
        
        <!-- p名称空间,走set方法
            1、导入p名称空间  xmlns:p="http://www.springframework.org/schema/p"
            2、使用p:属性完成注入
         -->
         <bean name="user3" class="domain.User" p:name="王五" p:age="22" p:Mycar-ref="car"></bean>
         
         <!-- spel注入:Spring Expression Language (Spring表达式语言) -->
         <bean name="user4" class="domain.User">
             <property name="name" value="#{user.name}"></property>
             <property name="age" value="#{user.age}"></property>
             <property name="Mycar" ref="car"></property>
         </bean>
         
         
         <!-- 复杂类型注入 -->
            <bean name="lmp" class="domain.Lmp">
                <!--Array数组注入 -->
                <property name="arr">            
                    <array>
                        <value>tom</value>
                        <value>jack</value>
                        <ref bean="user2"/>
                    </array>            
                </property>
                <!-- list集合注入 -->
                <property name="list">            
                    <list>
                        <value>zhangsan</value>
                        <value>lisi</value>
                        <ref bean="user3"/>
                    </list>
                </property>
                <!-- map集合注入 -->
                <property name="map">
                    <map>                    
                        <entry key="school" value="清华"></entry>
                        <entry key-ref="user" value-ref="car"></entry>
                    </map>
                </property>
                <!-- Properties类型注入 -->
                <property name="pro">
                    <props>
                        <prop key="school">北大</prop>
                        <prop key="name">张三</prop>
                    </props>
                </property>
            </bean>
    </beans>
        
    public class User {
    
        public User() {                
        }
        
        public User(String name,Integer age,Car car) {
            this.name=name;
            this.age=age;
            this.Mycar=car;
            
        }
        
        private String name;
        private Integer age;
        private Car Mycar;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public Car getMycar() {
            return Mycar;
        }
        public void setMycar(Car mycar) {
            Mycar = mycar;
        }
        
        @Override
        public String toString() {
            return "User [name=" + name + ", age=" + age + ", Mycar=" + Mycar + "]";
        }
    }
    public class Car {
        private String name;
        private String color;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getColor() {
            return color;
        }
        public void setColor(String color) {
            this.color = color;
        }
        @Override
        public String toString() {
            return "Car [name=" + name + ", color=" + color + "]";
        }
    }

    4、配置Spring容器生命周期

    <!-- 配置Spring容器随项目的启动而创建,随项目的关闭而销毁 -->
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <!-- 指定加载Spring配置文件的位置 -->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
      </context-param>

     5、在Web环境Struts2中使用Spring容器

    //1、获得ServletContext对象

    ServletContext sc = ServletActionContext.getServletContext();

    //2、从ServletContext中获得Spring容器

    WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);

    //3、从容器中获得对象

    ac.getBean("user");

  • 相关阅读:
    pid系统控制算法
    pandas+numpy 对df数据中的某列进行等分分桶操作
    pandas学习
    angular6 数组遍历项进行双向绑定 丢失焦点 问题解决
    TypeScript 之构造器 constructor 方法 methods
    公开便民信息网站收集
    C++11_线程池
    百度网盘信息
    【赵强老师】MongoDB中的索引(下)
    TDSQL 4001 备份故障处理案例
  • 原文地址:https://www.cnblogs.com/harriets-zhang/p/13453925.html
Copyright © 2011-2022 走看看