Spring框架基礎篇(一)

一、Spring框架

1.定義:是一個一站式的分層結構,輕量級開發框架
目前最受歡迎的框架
相當於一個對象管家,幫我們管理項目中用到的對象,就是一個容器

2.特點:
a.開元的
b.輕量級的(體積小的)
c.分成架構(按需要添加)
d.一站式(對目前流行的框架支持非常高)
3.作用:
 a.降低複雜性
 b.鬆耦合
 c.高性能
 d.已測試Junit
 e.聲明式事物
4.搭建過程
     1.下載需要的架包
     2.導入核心包 beans context expression core  logging(日誌包,不屬於核心包,但是必須有,不然報錯)
     3.創建編寫配置文件
         創建對象,交給Spring來管理
     4.創建ApplicationContext容器
     5.通過getBean來獲取到對象,如果對象不爲空,則Spring搭建成功
5.核心思想

 IOC原理:inverse of control 反轉控制
 1.定義:就是把對象的創建反轉(交給)給Spring來管理之前,我們手動new對象,現在是爲Spring拿對象
 2.實現原理:通過反射 + 配置文件 實現
 Class c = Class.forName("com.lnaou.Person");
  Object o = c.newIncetance();
  context.put("person",o);
  context.get("person");

 DI技術:dependency(依賴) injection(注入)

 依賴:類a中需要b類中提供的功能,這就是a依賴於b
 例如:service依賴dao
  UserService  
  UserDao dao = new UserDaoImplForJDBC();
   UserDao dao = new UserDaoImplForHibernate();
  使用Spring之後
  UserDao dao = context.getBean("userDaoimpl");
  //不需要改源代碼就能實現組件的切換

  注入:從外部把需要的對象放到內部
  UserService
  private UserDao dao;
  set and get;
  //依賴注入,最終目的就是提高程序的擴展性,儘可能不去修改源代碼
 6.bean的創建
  1.構造函數創建(默認,用這個)
  2.靜態工廠創建(調用指定的靜態方法獲取bean)
  3.實例工廠創建(調用實例方法獲取bean)
 7.依賴注入的四種方式
   1.set注入(就是通過set方法,所以必須有set方法)
   2.構造函數注入
   3.<:p的命名空間
   4.SpEL
 8.ApplicationContext 的兩個實列類
  ClassPathXMLApplicationContext 用於加載class路徑下的配置文件
  FileSystemXMLApplicationContext 加載系統路徑下的配置文件
 9.樑總容器
  XMLBeanFactory 獲取bean時才創建(不用)
  Application 加載配置時就創建
 10.bean元素屬性
  scope
   singleton      單例
   prototype      多例
   request        與request生命週期一致
   session        與session生命週期一致
   init-method    對象創建完了立即執行
   destroy-method 對象銷燬前執行
   id             和name作用相同
 11.複雜類型的注入
    array  使用array子標籤
         例如:<array>
         <value>123</value>,<value>456></value>
         </array>


    list 使用list子標籤 同array
       例如:<list>
         <value>123</value>,<value>456></value>
         </array>

   map 使用entry子標籤
    例如 <map>
     <entry key ="XX" value=""></entry>
     <entry key-ref="引用數據" value=""></entry>
     </map>

     properties使用props子標籤
     例如: 
     <props>
       <prop key="xx">value</prop>
     </props>
12.配置文件的模塊化
  當一個配置文件內容太多時,可以將其按照功能模塊劃分
  1.在創建容器時,傳入多個字符串對象(配置文件名)
  2.在配置文件中,使用import標籤導入

13.Spring作爲框架,當然不應該每次請求都創建一個新的
  希望Spring能夠跟隨項目的一併啓動,跟隨項目的停止一併銷燬
      實現步驟:
      1.在web.xml中配置監聽器,使得項目啓動時Spring也能夠一起啓動
      類名org.springframework.web.context/ContextLoaderListener
      當監聽到應用啓動時,會創建Spring容器並且放到ApplicationContext域中
      2.WebApplicationContextUtils工具用來從WEBApplication中取出Spring容器

二.代碼

Spring配置文件
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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
    xmlns:p="http://www.springframework.org/schema/p"

    >


 <bean name="personF" class="com.lanou.PersonFactory" >

   </bean>

   <!-- 使用靜態工廠方法創建對象時,得知道靜態方法在哪個類中 -->
   <bean class="com.lanou.Person" name="person">
      <!--1.set注入 屬性必須提供set方法 
        value屬性用於,注入基礎數據類型
        ref屬性用於,注入引用數據類型

      -->
      <property name="name" value="張三"></property>
      <property name="age" value="20"></property>   
      <property name="car" ref="car"></property>  
   </bean>

   <!--
    通過靜態工廠方法創建
   到PersonFactory中調用getPerson的靜態方法來獲取對象,並放入容器中
      如果使用默認的創建方式,Spring會到對應的類中找到空參構造函數
      如果指定了factory-method Spring就到類中找到指定的靜態方法執行
      class指定類型,可以與bean的類型不一致
     -->
   <bean name="person2" class="com.lanou.PersonFactory" factory-method="getPerson">
      <property name="name" value="王五"></property>
   </bean>


   <!--通過實例工廠方法創建
   到PersonFactory的某個對象中找getPerson2的方法,獲取返回對象,放入容器中


     -->
    <bean name="person3" class="com.lanou.PersonFactory" factory-method="getPerson2" factory-bean="personF">
      <property name="name" value="李六"></property>
   </bean>


    <!--讓Spring幫我們管理Person類的對象,這個對象的名字叫person
   class:全類名,要被管理的類的名字
   name:要被管理對象的名稱
    -->
    <bean class="com.lanou.Car" name="car">
         <property name="name" value="奧迪"></property>
          <property name="color" value="黑色"></property>
    </bean>

    <!-- _____________________________________________________ -->
    <!--2.構造函數注入 調用指定的構造函數並傳入參數是吸納注入  -->
    <bean name="person4" class="com.lanou.Person">
    <!-- name指定參數名,需要與構造函數一致 位置可換
      index 指定參數放到哪一個位置,當多個構造函數參數類相同,但是順序不同時
      type 指定參數類型,當多了構造函數的參數順序相同,但是數據類型不同時

    -->
     <constructor-arg name="car" ref="car" index="0"></constructor-arg>
        <constructor-arg name="name" value="10086" type="int"></constructor-arg>
        <constructor-arg name="age" value="35"></constructor-arg>
    </bean>


    <!-- _____________________________________________________ -->
    <!--p命名空間 
      需要先引入命名空間
        xmlns:p="http://www.springframework.org/schema/p"
     -->
    <bean name="person5" class="com.lanou.Person" 
     p:name="老王" p:age="50" p:car-ref="car">     
    </bean>

     <!-- _____________________________________________________ -->
     <!--SpEL的注入依賴
       SpEL  Spring 的表達式的變成語言,能夠實現一些簡單的邏輯
       與JSP的EL 一個性質

       -->
      <bean name="person6" class="com.lanou.Person">
      <!--找到一個叫person的對象,調用getName方法獲取數據  -->
           <property name="name" value="#{person.name}"></property>
           <property name="age" value="#{person5.age}"></property>
           <property name="car" ref="car"></property>
    </bean>


</beans>
Person類
package com.lanou;

public class Person {

private String name;
   private int age;
   private Car car;


   //空參構造函數
public Person() {
    System.out.println("空參構造函數RUN");
}
//使用構造函數注入,就需要提供帶參數的構造

public Person(String name, int age, Car car) {
    super();
    System.out.println("構造函數1");
    this.name = name;
    this.age = age;
    this.car = car;
}

public Person( Car car,String name, int age) {
    super();
    System.out.println("構造函數2");
    this.name = name;
    this.age = age;
    this.car = car;
}

public Person( Car car,int name, int age) {
    super();
    System.out.println("構造函數2");
    this.name = name+"";
    this.age = age;
    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 "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
}
 public void init() {
        System.out.println("person初始化");
 }
 public void destroy() {
    System.out.println("person銷燬方法");
 }
}
PersonFactory類
package com.lanou;

public class PersonFactory {
   //靜態工廠方式創建bean(當我們自己創建對象那個時使用)
    public static Person getPerson() {
        System.out.println("靜態工廠方法RUN");
        return new Person();
    }

    public  Person getPerson2() {
        System.out.println("實例工廠方法RUN");
        return new Person();
    }
}
Car類:
package com.lanou;

public class Car {

       private String name,color;

    public Car() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Car(String name, String color) {
        super();
        this.name = name;
        this.color = 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 + "]";
    }

}
CollectionBean類
package com.lanou;

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

public class CollectionBean {
    //演示覆雜數據類型的注入

   private Object[] array;
   private List list;
   private Map map;
   private Properties properties;

public Object[] getArray() {
    return array;
}
public void setArray(Object[] array) {
    this.array = array;
}
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 [array=" + Arrays.toString(array) + ", list=" + list + ", map=" + map + ", properties="
            + properties + "]";
}


}
HelloSpring獲取對象
package com.lanou;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring {
    public static void main(String[] args) {
        //想要從容器中,獲取被管理的對象
          //第一步,創建容器 (F4關係繼承圖)
           ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
           //2.從容器中獲取bean
           Person p = (Person)ac.getBean("person");
           System.out.println(p);  

          //獲取name爲person2的bean
           Person p2 = (Person)ac.getBean("person2");
           System.out.println(p2);

           //獲取name爲person3的bean set方法注入依賴
           Person p3 = (Person)ac.getBean("person3");
           System.out.println(p3);

           //獲取name爲person4的bean 構造函數注入依賴,其實也是調用了set方法,爲了簡化書寫
           Person p4 = (Person)ac.getBean("person4");
           System.out.println(p4);

         //獲取name爲person4的beanm  p命名空間注入依賴
           Person p5 = (Person)ac.getBean("person5");
           System.out.println(p5);

           Person p6 = (Person)ac.getBean("person6");
           System.out.println(p6);
    }
}
HelloSpring2獲取對象類
package com.lanou;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class HelloSpring2 {
    public static void main(String[] args) {
        //  ApplicationContext接口有兩個實現類
        //從類路徑下加載配置文件
        ApplicationContext ac1 = new ClassPathXmlApplicationContext("beans.xml");
   //從系統路徑下加載配置文件
        ApplicationContext ac2 = new FileSystemXmlApplicationContext("beans.xml");

          Person p1 = (Person)ac1.getBean("person");
          Person p2 = (Person)ac2.getBean("person");
          System.out.println(p1);
          System.out.println(p2);
    }
}

HelloSpring3獲取對象類
package com.lanou;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class HelloSpring3 {
  /*
   * Spring提供了兩種容器
   * 1.BeanFactroy(已過時)它是Spring框架最古老的接口
   *  僅定義了IOC DI基礎功能的接口
   *  特點:獲取bean時纔會創建對應的bean 以前的硬件設備資源匱乏,
   *  
   * 2.ApplicationContext
   *  它的功能更加強大
   *  特點:一旦加載配置文件就全部創建了
   *  
   */

    public static void main(String[] args) {
//       Resource resource = new FileSystemResource("/Users/lanou/javaweb/SpringDay01/src/beans.xml");
//      //  (file)Factory
//       BeanFactory factory = new XmlBeanFactory(resource );
//       System.out.println("配置加載完成");
//       System.out.println(factory.getBean("person"));

        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
//         ac.getBean("person1");
//         ac.getBean("person1");
//         ac.getBean("person1");

//         ac.getBean("person2");
//         //一般不用,關閉容器
//         ac.close();

        //獲取bean並輸出
           CollectionBean c = (CollectionBean)ac.getBean("cbean");
         System.out.println(c);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章