1. 程式人生 > >Spring4.0 學習筆記(一)

Spring4.0 學習筆記(一)

接受 主動 public sql drive 對象 ans article 種類

版權聲明:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/baidu_37181928/article/details/80020702

Spring 是什麽

  • Spring 是一個開源框架.
  • Spring 為簡化企業級應用開發而生. 使用 Spring 可以使簡單的 JavaBean 實現以前只有 EJB 才能實現的功能.
  • Spring 是一個 IOC(DI) 和 AOP 容器框架.

具體描述Spring

  • 輕量級:Spring 是非侵入性的 - 基於 Spring 開發的應用中的對象可以不依賴於 Spring 的 API
  • 依賴註入(DI — dependency injection、IOC)
  • 面向切面編程(AOP — aspect oriented programming)
  • 容器: Spring 是一個容器, 因為它包含並且管理應用對象的生命周期
  • 框架: Spring 實現了使用簡單的組件配置組合成一個復雜的應用. 在 Spring 中可以使用 XML 和 Java 註解組合這些對象
  • 一站式:在 IOC 和 AOP 的基礎上可以整合各種企業應用的開源框架和優秀的第三方類庫 (實際上 Spring 自身也提供了展現層的
    SpringMVC 和 持久層的 Spring JDBC)

IOC 和 DI

  • IOC(Inversion of Control):其思想是反轉資源獲取的方向. 傳統的資源查找方式要求組件向容器發起請求查找資源.作為回應, 容器適時的返回資源. 而應用了 IOC 之後, 則是容器主動地將資源推送給它所管理的組件,組件所要做的僅是選擇一種合適的方式來接受資源
    . 這種行為也被稱為查找的被動形式
  • DI(Dependency Injection) — IOC 的另一種表述方式:即組件以一些預先定義好的方式(例如: setter 方法)接受來自如容器的資源註入. 相對於 IOC 而言,這種表述更直接

IOC 容器

  • Spring IOC 容器讀取 Bean 配置創建 Bean 實例之前, 必須對它進行實例化. 只有在容器實例化後, 才可以從 IOC 容器裏獲取 Bean 實例並使用.
  • Spring 提供了兩種類型的 IOC 容器實現.
    • BeanFactory: IOC 容器的基本實現.
    • ApplicationContext: 提供了更多的高級特性. 是 BeanFactory 的子接口.
  • BeanFactory 是 Spring 框架的基礎設施,面向 Spring 本身;ApplicationContext 面向使用 Spring 框架的開發者,幾乎所有的應用場合都直接使用 ApplicationContext 而非底層的 BeanFactory
  • 無論使用何種方式, 配置文件是相同的.

開發環境的搭建

需要 jar 包

commons-logging-1.1.1.jar
spring-beans-4.0.2.RELEASE.jar
spring-context-4.0.2.RELEASE.jar
spring-core-4.0.2.RELEASE.jar
spring-expression-4.0.2.RELEASE.jar

Spring bean 的配置細節

applicationContext.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"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    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.xsd">
    <!-- 
        配置 bean 
        class: bean 的全類名, 通過反射的方法在 IOC 容器中創建 Bean, 使用必須要求有無參構造函數
        id: 標識容器中的 bean, id 唯一
    -->
    <bean id="hellospring" class="com.anqi.hello.HelloSpring">
        <property name="name" value="anqi"></property>
    </bean>

    <!-- 通過構造方法來配置 bean 的屬性 -->
    <bean id="car" class="com.anqi.hello.Car">
        <constructor-arg value="Audi" index="0"></constructor-arg>
        <constructor-arg value="Shanghai" index="1"></constructor-arg>
        <constructor-arg value="300000" index="2"></constructor-arg>
    </bean>

    <!-- 使用構造器註入屬性值可以指定參數的位置和參數的類型! 以區分重載的構造器! -->
    <bean id="car2" class="com.anqi.hello.Car">
        <constructor-arg value="Baoma" index="0"></constructor-arg>
        <constructor-arg value="Shanghai" index="1"></constructor-arg>
        <constructor-arg value="240" type="int"></constructor-arg>
    </bean>

    <bean id="car3" class="com.anqi.hello.Car">
        <constructor-arg value="Baoma3" index="0"></constructor-arg>
        <!-- 如果字面值包含特殊字符 可以用<![CDATA[]]> 包裹起來 -->
        <!-- 字面值就是基本數據類型及其包裝類, 以及 String 類 -->
        <!-- 屬性值也可以使用 value 節點來進行配置 -->
        <constructor-arg index="1">
            <value><![CDATA[<shanghai3]]></value>
        </constructor-arg>
        <constructor-arg value="2403" type="int"></constructor-arg>
    </bean>

    <bean id = "person" class = "com.anqi.hello.Person">
        <property name="name" value="Anqi"></property>
        <property name="age">
            <value>25</value>
        </property>

        <!-- <property name="car" ref="car2"></property> 與下面代碼效果一致-->
        <!-- 
        <property name="car">
            <ref bean="car2"/>
        </property>
         -->

        <!-- 內部 bean 不能被外部引用, 只能在內部使用-->
        <property name="car">
            <bean class="com.anqi.hello.Car">
                <constructor-arg value="fute"></constructor-arg>
                <constructor-arg value="Beijing"></constructor-arg>
                <constructor-arg value="28000" type="double"></constructor-arg>
            </bean>
        </property>
    </bean>

    <bean id="person2" class="com.anqi.hello.Person">
        <constructor-arg value="LiChen"></constructor-arg>
        <constructor-arg value="18"></constructor-arg>
        <!-- 測試賦值 NULL 值 -->
        <!--<constructor-arg><null/></constructor-arg>  -->

        <constructor-arg name="car" ref="car2"></constructor-arg>
        <!-- 為級聯屬性賦值,必須有對應的 setter 方法 -->
        <!-- 註意 : 屬性需要先初始化後才可以為級聯屬性賦值, 否則會有異常 -->
        <property name="car.maxSpeed" value="220"></property>
    </bean> 

    <bean id="person3" class="com.anqi.hello.collections.Person">
        <property name="name" value="Angels"></property>
        <property name="age" value="23"></property>
        <property name="cars">
            <!-- 使用 list 節點來為 List 類型的屬性賦值 -->
            <list>
                <ref bean="car"/>
                <ref bean="car2"/>
                <bean class="com.anqi.hello.Car">
                    <constructor-arg value="fute2"></constructor-arg>
                    <constructor-arg value="Beijing2"></constructor-arg>
                    <constructor-arg value="280002" type="double"></constructor-arg>
                </bean>
            </list>
        </property>
    </bean>

    <!-- 配置 Map 屬性值 -->
    <bean id="newPerson" class="com.anqi.hello.collections.NewPerson">
        <property name="name" value=‘ANAN‘></property>
        <property name="age" value="18"></property>

        <property name="cars">
            <!-- 使用 map 節點及 map 的 entry 子節點配置 Map 類型的成員變量 -->
            <map>
                <entry key="AA" value-ref="car2"></entry>
                <entry key="BB" value-ref="car3"></entry>
            </map>
        </property>
    </bean>

    <!-- 配置 Properties 屬性值 -->
    <bean id="datasource" class="com.anqi.hello.collections.DataSource">
        <property name="properties">
            <!-- 使用 props 和 prop 子節點為 Properties 屬性賦值 -->
            <props>
                <prop key="user">root</prop>
                <prop key="password">12345</prop>
                <prop key="jdbcUrl">jdbc:mysql:///javaee</prop>
                <prop key="driverManger">com.mysql.jdbc.Driver</prop>
            </props>
        </property>
    </bean>

    <!-- 配置獨立的集合 bean, 以供多個 bean 進行引用, 需要導入 utill 命名空間 -->
    <!-- 使用不帶版本號的 util 命名空間,否則會報錯 -->
    <util:list id="cars">
        <ref bean="car"/>
        <ref bean="car2"/>
    </util:list>
    <bean id="person4" class="com.anqi.hello.collections.Person">
        <property name="name" value="anyixuan"></property>
        <property name="age" value="5"></property>
        <property name="cars" ref="cars"></property>
    </bean>


    <!-- 通過 p 命名空間為 bean 的屬性賦值, 需要先導入 p 命名空間, 相對於傳統的配置方式更加的簡潔。 -->
    <bean id="person5" class="com.anqi.hello.collections.Person" p:age="30" p:name="Queen"
        p:cars-ref="cars">
    </bean>
</beans>


Car.java

package com.anqi.hello;

public class Car {

    private String brand;
    private String corp;
    private double price;
    private int maxSpeed;

    public Car(String brand, String corp, double price) {
        super();
        this.brand = brand;
        this.corp = corp;
        this.price = price;
    }

    public Car(String brand, String corp, int maxSpeed) {
        super();
        this.brand = brand;
        this.corp = corp;
        this.maxSpeed = maxSpeed;
    }
    //....setter getter toString
}


Person.java

package com.anqi.hello;

public class Person {

    private String name;
    private int age;
    private Car car;
    public Person(String name, int age, Car car) {
        super();
        this.name = name;
        this.age = age;
        this.car = car;
    }
    public Person() {
        super();
    //....setter getter toString
}


Main.java

package com.anqi.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {

        //1. 創建 Spring 的 IOC 容器對象
        //ApplicationContext 代表 IOC 容器
        //ClassPathXmlAppolicationContext : ApplicationContext 接口的實現類,該實現類從類路徑下來加載文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        //2. 從 IOC 容器中獲取 Bean 的實例

        //利用 id 定位到 IOC 容器中的 Bean
        HelloSpring helloSpring = (HelloSpring) ctx.getBean("hellospring");

        //利用類型返回 IOC 容器中的 Bean, 但要求 IOC 容器中必須只能有一個該類型的 Bean
        //HelloSpring helloSpring = ctx.getBean(HelloSpring.class);
        //3. 調用 hello 方法
        helloSpring.hello();

        Car car = (Car) ctx.getBean("car");
        System.out.println(car);
        //Car [brand=Audi, corp=Shanghai, price=300000.0, maxSpeed=0]

        car = (Car) ctx.getBean("car2");
        System.out.println(car);
        //Car [brand=Baoma, corp=Shanghai, price=0.0, maxSpeed=240]

        car = (Car) ctx.getBean("car3");
        System.out.println(car);
        //Car [brand=Baoma3, corp=<shanghai3, price=0.0, maxSpeed=2403]

        Person p = (Person) ctx.getBean("person");
        System.out.println(p);
        //Person [name=Anqi, age=25, car=Car [brand=Baoma, corp=Shanghai, price=0.0, maxSpeed=240]]

        p = (Person) ctx.getBean("person2");
        System.out.println(p);
        //Person [name=LiChen, age=18, car=Car [brand=Baoma, corp=Shanghai, price=0.0, maxSpeed=220]]
    }
}


com.anqi.hello.collections 下的
Person.java

package com.anqi.hello.collections;
import java.util.List;
import com.anqi.hello.Car;
public class Person {

    private String name;
    private int age;
    private List<Car> cars;
    public Person(String name, int age, List<Car> cars) {
        super();
        this.name = name;
        this.age = age;
        this.cars = cars;
    }
    public Person() {
        super();
    }
    //....setter getter toString
}


NrePerson.java

package com.anqi.hello.collections;
import java.util.Map;
import com.anqi.hello.Car;
public class NewPerson {

    private String name;
    private int age;
    private Map<String, Car> cars;
    public NewPerson(String name, int age, Map<String, Car> cars) {
        super();
        this.name = name;
        this.age = age;
        this.cars = cars;
    }
    public NewPerson() {
        super();
    }
    //....setter getter toString

}


DataSource.java

package com.anqi.hello.collections;
import java.util.Properties;
public class DataSource {
    private Properties properties;

    public Properties getProperties() {
        return properties;
    }

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

    public String toString() {
        return "DataSource [properties=" + properties + "]";
    }


}

Main.java

package com.anqi.hello.collections;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String [] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        Person person3 = (Person) ctx.getBean("person3");
        System.out.println(person3);
        //Person [name=Angels, age=23, cars=[Car [brand=Audi, corp=Shanghai, price=300000.0, maxSpeed=0],
        //Car [brand=Baoma, corp=Shanghai, price=0.0, maxSpeed=220], Car [brand=fute2, corp=Beijing2, 
        //price=280002.0, maxSpeed=0]]]

        NewPerson newPerson = (NewPerson) ctx.getBean("newPerson");
        System.out.println(newPerson);
        //NewPerson [name=ANAN, age=18, cars={AA=Car [brand=Baoma, corp=Shanghai, price=0.0, maxSpeed=220], 
        //BB=Car [brand=Baoma3, corp=<shanghai3, price=0.0, maxSpeed=2403]}]

        DataSource dataSource = (DataSource) ctx.getBean("datasource");
        System.out.println(dataSource);
        //DataSource [properties={user=root, password=12345, driverManger=com.mysql.jdbc.Driver, 
        //jdbcUrl=jdbc:mysql:///javaee}]

        Person person4 = (Person) ctx.getBean("person4");
        System.out.println(person4);
        //Person [name=anyixuan, age=5, cars=[Car [brand=Audi, corp=Shanghai, price=300000.0, maxSpeed=0], 
        //Car [brand=Baoma, corp=Shanghai, price=0.0, maxSpeed=220]]]

        Person person5 = (Person) ctx.getBean("person5");
        System.out.println(person5);
        //Person [name=Queen, age=30, cars=[Car [brand=Audi, corp=Shanghai, price=300000.0, maxSpeed=0], 
        //Car [brand=Baoma, corp=Shanghai, price=0.0, maxSpeed=220]]]
    }
}

--------------------- 本文來自 海向 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/baidu_37181928/article/details/80020702?utm_source=copy

Spring4.0 學習筆記(一)