Spring 學習筆記01,spring學習筆記01
1.Spring 簡介
Spring 是為企業提供的一個輕量級的解決方案,包括:基於依賴注入的核心機制,基於AOP的聲明式交易管理,
與多種持久層技術的集合以及優秀的WEB MVC架構等。
Spring 架構的組成結構:
2.Spring 準備工作
1)首先在官網下載Spring 壓縮檔並解壓
2)將jar包匯入eclipse的項目中
3.Spring 的使用
Spring 核心容器就是一個超級大工廠,所有的對象都被當成Spring核心容器管理的對象,稱為Bean。
首先定義兩個類 Pen 和 Person:
public class Pen { public String write(){ return "用筆寫字"; } }
public class Person { private Pen pen; public void setPen(Pen pen){ this.pen = pen; } public void usePen(){ System.out.println("我要寫字"); System.out.println(pen.write()); }}
Person中userPen()方法中用到了Pen的write()方法,也就是Person依賴於Pen,Sring就是處理這些Bean的對象之間的依賴和對象的建立的。
因此在src目錄下面建立applicationContext.xml檔案,並配置相關的bean:
<?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:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <bean id="person" class="com.huan.example.Person"> <property name="pen" ref="pen"></property> </bean> <bean id="pen" class="com.huan.example.Pen"></bean></beans>
Spring會根據設定檔的bean通過反射機制調用該類的無參構造建立對象,並以id作為key值放入到Sring容器中,稱為Spring中的Bean 。
Person中的<property>子項目,Spring會利用反射執行Person中的setter方法,也就是setPen()方法,將ref指向的pen這個Bean作為參數注入到
Person中。
建立一個類進行測試:
public class TestPerson { public static void main(String[] args) { //載入設定檔,建立Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //根據id擷取相應的Bean對象,不需要new Person p = ac.getBean("person", Person.class); //調用對象的方法 p.usePen(); }}
ApplicationContext 介面主要有實作類別:ClassPathXmlApplicationContext 和 FileSystemXmlApplicationContext,前者是
在類載入路徑下搜尋設定檔,後者是在檔案系統的相對路徑或絕對路徑下搜尋設定檔。
運行測試類別結果:
從上面可以看出使用了Spring架構之後不再使用new調用構造器建立對象,所有的java對象都由Spring容器負責建立。