Spring框架基础

Posted XDZY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring框架基础相关的知识,希望对你有一定的参考价值。

Spring框架基础

测试Spring的IOC(控制反转)和DI(依赖注入)

 

为了防止每次创建对象都要创建一个Spring容器,所以在xml中加一个监听器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 让我们的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>
</web-app>

 

0.导包

 

1.创建配置文件

<?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="com.bean.User">
        <!-- 值类型注入 -->
        <property name="name" value="xdzy"/>
        <property name="age" value="18"/>
        <!-- 引用类型注入 -->
        <property name="car" ref="car"/>
    </bean>

    <!-- 将car对象配置到spring容器 -->
    <bean name="car" class="com.bean.Car">
        <property name="name" value="兰博基尼"/>
        <property name="color" value="红色"/>
    </bean>

    <!-- 构造函数注入 -->
    <bean name="user1" class="com.bean.User">
        <!-- 当构造方法参数位置不同,可以通过index确定参数位置 -->
        <!-- 当构造方法参数类型不同,可以通过type确定参数类型 -->
        <constructor-arg name="name" value="xdzy" index="0" type="java.lang.String"/>
        <constructor-arg name="car" ref="car"/>
    </bean>

    <!-- p属性注入 -->
    <!-- 需加入xmlns:p="http://www.springframework.org/schema/p" -->
    <bean name="user2" class="com.bean.User" p:name="xdzy" p:age="18" p:car-ref="car"/>

    <!-- spel表达式注入;可以实现动态注入 -->
    <bean name="user3" class="com.bean.User">
        <property name="name" value="#{user.name}"/>
        <property name="age" value="#{user2.age}"/>
        <property name="car" ref="car"/>
    </bean>

    <!-- 数组注入 -->
    <bean name="cb" class="com.bean.CollectionBean">
        <!-- 只有一个值时 -->
        <!--<property name="arr" value="tom"/>-->
        <!-- 多值多元素注入 -->
        <property name="arr">
            <array>
                <value>xdzy</value>
                <value>jady</value>
                <ref bean="user3"/>
            </array>
        </property>
    </bean>

    <!-- 集合注入 -->
    <bean name="cb2" class="com.bean.CollectionBean">
        <!-- 只有一个值时 -->
        <!--<property name="list" value="tom"/>-->
        <!-- 多值多元素注入 -->
        <property name="list">
            <list>
                <value>xdzy</value>
                <value>jady</value>
                <ref bean="user3"/>
            </list>
        </property>
    </bean>

    <!-- map注入 -->
    <bean name="cb3" class="com.bean.CollectionBean">
        <property name="map">
            <map>
                <entry key="name" value="xdzy"/>
                <entry key="user" value-ref="user3"/>
                <entry key-ref="user1" value-ref="user2"/>
            </map>
        </property>
    </bean>

    <!-- 资源注入 -->
    <bean name="cb4" class="com.bean.CollectionBean">
        <property name="properties">
            <props>
                <prop key="driverClass">com.jdbc.mysql.Driver</prop>
                <prop key="userName">admin</prop>
                <prop key="password">123</prop>
            </props>
        </property>
    </bean>
</beans>
<?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">

    <!-- spring:管理对象的容器 -->
    <!-- spring IOC:控制反转,通过spring创建对象(无需手动创建) -->
    <!-- DI:依赖注入;就是给对象的某些属性赋值 -->

    <!-- 将User对象交给spring管理 -->
    <!-- bean元素:描述需要spring管理的对象;name属性:给对象取个别名,获取对象时需要;
        class属性:被管理对象的完整类名;id属性:与name属性一模一样,不可重复,不能使用特殊字符(因此要name)-->
    <!-- 创建方式一:spring调用无参构造创建对象 -->
    <!-- scope:singleton:表示单例对象,在spring容器中只会存在一个实例 -->
    <!-- scope:prototype:表示多例对象,每次获取都会创建一个新的对象;整合struts2时必须为多例 -->
    <!-- 生命周期方法配置init,destroy -->
    <bean name="user" class="com.bean.User" scope="singleton" init-method="init" destroy-method="destroy"></bean>

    <!-- 创建方式二:通过静态工厂的某个方法创建一个user对象 -->
    <bean name="user1" class="com.bean.UserFactory" factory-method="createUser"></bean>

    <!-- 创建方式三:实例工厂创建对象 -->
    <bean name="user2" factory-bean="userFactory" factory-method="createUser2"></bean>
    <bean name="userFactory" class="com.bean.UserFactory"></bean>

    <!-- 模块化配置,可以导入其他spring配置文件 -->
    <!--<import resource="applicationContext.xml"/>-->
</beans>

 

2.相应的实体类

package com.bean;

/**
 * @author: XDZY
 * @date: 2018/9/5 23:38
 * @description: 车辆实体类
 */
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 + \'\\\'\' +
                \'}\';
    }
} 
package com.bean;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author: XDZY
 * @date: 2018/9/6 07:56
 * @description: 复杂类型注入
 */
public class CollectionBean {
    /**
     * 数组
     */
    private Object[] arr;
    /**
     * 集合
     */
    private List list;
    /**
     * map集合
     */
    private Map map;
    /**
     * 资源文件
     */
    private Properties properties;

    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 getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "CollectionBean{" +
                "arr=" + Arrays.toString(arr) +
                ", list=" + list +
                ", map=" + map +
                ", properties=" + properties +
                \'}\';
    }
}
package com.bean;

/**
 * @author: XDZY
 * @date: 2018/9/5 19:31
 * @description: 用户实体类
 */
public class User {
    private String name;
    private int age;
    private Car car;

    public void init() {
        System.out.println("初始化方法");
    }

    public void destroy() {
        System.out.println("销毁方法");
    }

    public User() {
        System.out.println("无参构造创建一个对象");
    }

    public User(String name, Car car) {
        System.out.println("构造函数注入");
        this.name = name;
        this.car = car;
    }

    public User(Car car, String name) {
        System.out.println("构造函数注入2");
        this.name = name;
        this.car = car;
    }

    public User(Integer name, Car car) {
        System.out.println("构造函数注入3");
        this.name = name + "";
        this.car = car;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name=\'" + name + \'\\\'\' +
                ", age=" + age +
                ", car=" + car +
                \'}\';
    }
}
package com.bean;

/**
 * @author: XDZY
 * @date: 2018/9/5 22:56
 * @description: UserFactory
 */
public class UserFactory {
    public static User createUser() {
        System.out.println("静态工厂创建对象");
        return new User();
    }

    public User createUser2() {
        System.out.println("实例工厂创建对象");
        return new User();
    }
}

 

3.相应的测试类

package com.test;

import com.bean.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author: XDZY
 * @date: 2018/9/5 19:59
 * @description: 测试能否从xml中获取对象
 */
public class Demo1 {
    /**
     * 调用无参创建对象
     */
    @Test
    public void test() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取user对象
        /*User user=(User)ac.getBean("user");
        System.out.println(user);*/
    }

    /**
     * 静态工厂创建对象
     */
    @Test
    public void test1() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取user对象
        User user = (User) ac.getBean("user1");
        System.out.println(user);
    }

    /**
     * 实例工厂创建对象
     */
    @Test
    public void test2() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取user对象
        User user = (User) ac.getBean("user2");
        System.out.println(user);
    }
}
package com.test;

import com.bean.CollectionBean;
import com.bean.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author: XDZY
 * @date: 2018/9/5 19:59
 * @description: 给属性注入值
 */
public class Demo2 {
    /**
     * set
     */
    @Test
    public void test() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bean/applicationContext.xml");
        //获取user对象
        User user = (User) ac.getBean("user");
        System.out.println(user);
    }

    /**
     * 构造
     */
    @Test
    public void test1() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bean/applicationContext.xml");
        //获取user对象
        User user = (User) ac.getBean("user1");
        System.out.println(user);
    }

    /**
     * p属性
     */
    @Test
    public void test2() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bean/applicationContext.xml");
        //获取user对象
        User user = (User) ac.getBean("user2");
        System.out.println(user);
    }

    /**
     * spel
     */
    @Test
    public void test3() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bean/applicationContext.xml");
        //获取user对象
        User user = (User) ac.getBean("user3");
        System.out.println(user);
    }

    /**
     * 数组or集合
     */
    @Test
    public void test4() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bean/applicationContext.xml");
        //获取user对象
        CollectionBean cb = (CollectionBean) ac.getBean("cb2");
        System.out.println(cb);
    }

    /**
     * map
     */
    @Test
    public void test5() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bean/applicationContext.xml");
        //获取user对象
        CollectionBean cb = (CollectionBean) ac.getBean("cb3");
        System.out.println(cb);
    }

    /**
     * 资源
     */
    @Test
    public void test6() {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bean/applicationContext.xml");
        //获取user对象
        CollectionBean cb = (CollectionBean) ac.getBean("cb4");
        System.out.println(cb);
    }
}

 

以上是关于Spring框架基础的主要内容,如果未能解决你的问题,请参考以下文章

java:Spring框架1(基本配置,简单基础代码实现)

Spring基础知识

Spring 基础入门

Spring基础

spring初学

Spring 框架基础(06):Mvc架构模式简介,执行流程详解