java框架之Spring(1)-入門

介紹

概述

Spring 是一個開放源代碼的設計層面框架,它解決的是業務邏輯層和其餘各層的鬆耦合問題,所以它將面向接口的編程思想貫穿整個系統應用。Spring 是於 2003 年興起的一個輕量級的 Java 開發框架,由 Rod Johnson 建立。簡單來講,Spring 是一個分層的 JavaSE/EE full-stack (一站式) 輕量級開源框架。html

下載

點擊下載,我這裏使用的版本是 4.2.4,百度網盤下載java

入門

IoC

控制反轉(Inversion of Control,縮寫爲 IoC),是面向對象編程中的一種設計原則,能夠用來減低計算機代碼之間的耦合度。其中最多見的方式叫作依賴注入(Dependency Injection,簡稱 DI),還有一種方式叫「依賴查找」(Dependency Lookup)。經過控制反轉,對象在被建立的時候,由一個調控系統內全部對象的外界實體,將其所依賴的對象的引用傳遞給它。也能夠說,依賴被注入到對象中。web

理解 IoC 和 DI :

IoC :控制反轉,將對象的建立權交給了 Spring。spring

DI :依賴注入,前提必須有 IoC 的環境,Spring 管理一個類時將類依賴的屬性注入(設置)進來,就是 DI 的過程。編程

引入jar包

添加配置文件

在 src 下添加名爲 'applicationContext.xml' 的配置文件,內容以下:session

<?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-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html 下能夠找到-->
</beans>

簡單使用

package com.zze.dao;

public interface UserDao {
    void  save();
}
com.zze.dao.UserDao
package com.zze.dao.impl;

import com.zze.dao.UserDao;

public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        System.out.println("from UserDaoImpl.save()");
    }
}
com.zze.dao.impl.UserDaoImpl
<?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-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html 下能夠找到-->
    <bean id="userDao" class="com.zze.dao.impl.UserDaoImpl"></bean>
</beans>
applicationContext.xml
/**
 * 原有方式建立 Bean
 */
@Test
public void test1(){
    UserDao userDao = new UserDaoImpl();
    userDao.save();
}

/**
 * 從 Spring 中獲取 Bean
 */
@Test
public void test2(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserDao userDao = (UserDao) applicationContext.getBean("userDao");
    userDao.save();
}
test

Spring的工廠類

BeanFactory :老版本的工廠類,調用 getBean 時纔會生成類的實例。app

ApplicationContext :新版本的工廠類,加載配置文件時就會將 Spring 管理的類實例化。框架

ApplicationContext 有兩個實現類:
  1. ClassPathXmlApplicationContext :加載類路徑下的配置文件。
  2. FileSystemXmlApplicationContext :加載文件系統下的配置文件。

配置相關

Bean標籤

屬性:webapp

  • id :使用了惟一約束,不能出現特殊字符。 
  • name :沒有使用惟一約束(理論上是能夠出現重複的,可是實際開發中是不能出現的),能夠出現特殊字符。
  • init-method :初始化時執行該方法(在構造方法以後)。
  • destroy-method :銷燬時執行該方法(默認狀況下 Spring 建立的 Bean 是單例的,在工廠類 ApplicationContext 實例 Close 時執行)。
  • scope :配置 Bean 的做用範圍。
    scope 有以下幾個可選值:

        singleton :默認值,Spring 會採用單例模式建立這個對象。ide

        prototype :多例的。

        request :應用在 web 項目中,Spring 建立這個類對象後,將這個對象存放到 request 範圍中。

        session :應用在 web 項目中,Spring 建立這個類對象後,將這個對象存放的 session 範圍中。

        globalsession :應用在 web 項目中,必須在 porlet 環境下使用。

Spring的屬性注入

爲方便下面測試,先新建以下類:

package com.zze.bean;

public class Department {
    public Department() {
    }

    public Department(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Department{" +
                "name='" + name + '\'' +
                '}';
    }
}
com.zze.bean.Department
package com.zze.bean;

public class User {

    public User() {
    }

    public User(String name, Integer age, Department department) {
        this.name = name;
        this.age = age;
        this.department = department;
    }

    private String name;
    private Integer age;
    private Department department;

    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 Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

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

構造方法注入

<bean name="department" class="com.zze.bean.Department">
    <constructor-arg name="name" value="信息部"/>
</bean>

<bean name="user" class="com.zze.bean.User">
    <constructor-arg name="name" value="李四"/>
    <constructor-arg name="age" value="30"/>
    <constructor-arg name="department" ref="department"/>
</bean>
@Test
public void test1() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Object user = applicationContext.getBean("user");

    System.out.println(user);
    /*
    User{name='李四', age=30, department=Department{name='信息部'}}
     */
}
test

set方法注入

<bean name="department" class="com.zze.bean.Department">
    <property name="name" value="信息部"/>
</bean>

<bean name="user" class="com.zze.bean.User">
    <property name="name" value="張三"/>
    <property name="age" value="12"/>
    <property name="department" ref="department"/>
</bean>
@Test
public void test2() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Object user = applicationContext.getBean("user");
    System.out.println(user);
    /*
    User{name='張三', age=12, department=Department{name='信息部'}}
     */
}
test

p名稱空間注入

<!--
    在 Spring 2.5 以後支持。
    需在 beans 標籤中添加屬性 xmlns:p="http://www.springframework.org/schema/p" 來引入 p 名稱空間
-->
<bean name="department" class="com.zze.bean.Department" p:name="信息部"/>

<bean name="user" class="com.zze.bean.User" p:name="張三" p:age="21" p:department-ref="department"/>
@Test
public void test3() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Object user = applicationContext.getBean("user");
    System.out.println(user);
    /*
    User{name='張三', age=21, department=Department{name='信息部'}}
     */
}
test

SpEL注入

<!--
    在 Spring 3.0 以後支持。
-->
<bean name="department" class="com.zze.bean.Department">
    <property name="name" value="#{'推广部'}"/>
</bean>

<bean name="user" class="com.zze.bean.User">
    <property name="name" value="#{'李四'}"/>
    <!--在表達式中能夠有計算操做,而且能夠直接調用對象屬性及方法-->
    <property name="age" value="#{10+22}"/>
    <property name="department" ref="department"/>
</bean>
@Test
public void test4() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Object user = applicationContext.getBean("user");
    System.out.println(user);
    /*
    User{name='李四', age=32, department=Department{name='推广部'}}
     */
}
test
注入 Array 類型:
package com.zze.bean;

import java.util.Arrays;

public class Customer {
    private String name;
    private String[] hobbies;

    public String getName() {
        return name;
    }

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

    public String[] getHobbies() {
        return hobbies;
    }

    public void setHobbies(String[] hobbies) {
        this.hobbies = hobbies;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "name='" + name + '\'' +
                ", hobbies=" + Arrays.toString(hobbies) +
                '}';
    }
}
com.zze.bean.Customer
<!--
    List 和 Set 的注入方式與 Array 一致
-->
<bean name="customer" class="com.zze.bean.Customer">
    <property name="name" value="二狗"/>
    <property name="hobbies">
        <list>
            <value>吃飯</value>
            <value>睡覺</value>
            <value>打豆豆</value>
        </list>
    </property>
</bean>
@Test
public void test5() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Object user = applicationContext.getBean("customer");
    System.out.println(user);
    /*
    Customer{name='二狗', hobbies=[吃飯, 睡覺, 打豆豆]}
    */
}
test
注入 Map 類型:
package com.zze.bean;

import java.util.Map;

public class TestBean {
    private Map<String, Object> map;

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return "TestBean{" +
                "map=" + map +
                '}';
    }
}
com.zze.bean.TestBean
<bean id="testBean" class="com.zze.bean.TestBean">
    <property name="map">
        <map>
            <entry key="1" value="a"/>
            <entry key="2" value="b"/>
            <entry key="3" value="c"/>
        </map>
    </property>
</bean>
@Test
public void test6(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Object testBean = applicationContext.getBean("testBean");
    System.out.println(testBean);
    /*
    TestBean{map={1=a, 2=b, 3=c}}
     */
}
test

分模塊配置

第一種方式是在建立工廠實例時一次性加載全部指定的配置文件,例:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext1.xml","applicationContext2.xml");

第二種方式是經過配置文件中的 import 標籤引入其它的配置文件,例:

<import resource="com/zze/dao/applicationContext-dao.xml"/>
相關文章
相關標籤/搜索