Spring是一個JavaEE輕量級的一站式開發框架。
JavaEE: 就是用於開發B/S的程序。(企業級)
輕量級:使用最少代碼啓動框架,而後根據你的需求選擇,選擇你喜歡的模塊使用。
重量級:早期有的EJB,開發一個HelloWorld程序都須要引入EBJ的所有模塊
一站式:Spring框架提供涵蓋了JavaEE開發的表示層,服務層,持久層的全部組件功能。也就是說,原則上,學完一套Spring框架,不用其餘框架就能夠完成網站一條流程的開發。可是Spring仍然能夠和其餘的框架無縫整合。java
輕量:Spring 是輕量的,就是除內核模塊(4個jar),其餘模塊由開發者自由選擇使用,同時支持整合其餘框架。也能夠稱爲就是可插拔式開發框架,像插頭和插座同樣,插上就用。這就是Spring框架核心理念(Ioc)。
控制反轉:Spring經過控制反轉實現了鬆散耦合,對象們給出它們的依賴,而不是建立或查找依賴的對象們。
面向切面的編程(AOP):Spring支持面向切面的編程,而且把應用業務邏輯和系統服務分開。
容器:Spring 包含並管理應用中對象的生命週期和配置。
MVC框架:Spring的WEB框架是個精心設計的框架,是Web框架的一個很好的替代品。
事務管理:Spring 提供一個持續的事務管理接口,能夠擴展到上至本地事務下至全局事務(JTA)。
異常處理:Spring 提供方便的API把具體技術相關的異常(好比由JDBC,Hibernate or JDO拋出的)轉化爲一致的unchecked 異常。web
Spring強調的理念是,輕量級。Spring的輕量級主要體如今模塊的可插拔,Spring提供的功能模塊,除了內核模塊之外,開發人員能夠選擇性使用。因此,Spring框架在現實開發中,主要的功能用於整合各類開發框架開發項目。spring
Spring官方網站:https://spring.io/sql
Spring官方提供的Maven方式的項目下載:https://start.spring.io/
可是基於簡單入門的原則,咱們要經過導入包的方式來學習。須要下載框架的zip包
地址爲:http://repo.springsource.org/libs-release-local/org/springframework/spring/數據庫
根目錄:express
jar包:編程
包說明:api
包名 | 說明 |
spring-aop-4.3.2.RELEASE.jar | 實現了AOP的支持 |
spring-aspects-4.3.2.RELEASE.jar | AOP框架aspects支持包 |
spring-beans-4.3.2.RELEASE.jar | 內核支撐包,實現了處理基於xml對象存取 |
spring-context-4.3.2.RELEASE.jar | 內核支撐包,實現了Spring對象容器 |
spring-context-support-4.3.2.RELEASE.jar | 容器操做擴展包,擴展了一些經常使用的容器對象的設置功能 |
spring-core-4.3.2.RELEASE.jar | 內核支撐包,Spring的內核 |
spring-expression-4.3.2.RELEASE.jar | 內核支撐包,實現了xml對Spring表達式的支持 |
spring-instrument-4.3.2.RELEASE.jar | 提供了一些類加載的的工具類 |
spring-instrument-tomcat-4.3.2.RELEASE.jar | 提供了一些tomcat類加載的的工具類,實現對應Tomcat服務的調用 |
spring-jdbc-4.3.2.RELEASE.jar | SpringJDBC實現包,一個操做數據庫持久層的子框架 |
spring-jms-4.3.2.RELEASE.jar | 集成jms的支持,jms:Java消息服務。 |
spring-messaging-4.3.2.RELEASE.jar | 集成messaging api和消息協議提供支持 |
spring-orm-4.3.2.RELEASE.jar | ORM框架集成包,實現了Hibernate,IBatis,JDO的集成。 |
spring-oxm-4.3.2.RELEASE.jar | Spring OXM對主流O/X Mapping框架作了一個統一的抽象和封裝。就是對應XML讀寫框架的支持 |
spring-test-4.3.2.RELEASE.jar | Spring集成JUnit測試 |
spring-tx-4.3.2.RELEASE.jar | 事務代理的支持 |
spring-web-4.3.2.RELEASE.jar | SpringWeb通用模塊 |
spring-webmvc-4.3.2.RELEASE.jar | SpringMVC子框架 |
spring-webmvc-portlet-4.3.2.RELEASE.jar | Spring對門戶技術(portlet)的支持 |
spring-websocket-4.3.2.RELEASE.jar | Spring對websocket的支持 |
注:紅色部分爲基礎核心包,使用Spring必須導入數組
Spring之因此能夠實現模塊的可插拔是支持依賴注入,所謂的依賴注入/控制反轉就是不用new就能夠建立對象。tomcat
使用Spring框架不用new建立一個對象:
1.建立項目並導入jar包:將Spring的基礎支撐包和依賴的日誌包複製到lib文件下,而且加入項目中
2.建立配置文件
在項目的src下面建立配置文件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"> </beans>
3.建立對象到Spring容器中
建立一個類
package com.gjs.service; public class HelloSpringService { public void say() { System.out.println("你好!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"> <!-- <bean id="" class = ""> 配置讓spring管理類的對象的建立 id : 惟一標識 class :被管理類的全限定名 --> <bean id="HelloSpringService" class="com.gjs.service.HelloSpringService"/> </beans>
測試類, 使用getBean方法得到容器中的對象。
package com.gjs.test; import static org.junit.Assert.*; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.gjs.service.HelloSpringService; public class TestSpring { @Test public void testName() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloSpringService helloSpringService = context.getBean("HelloSpringService",HelloSpringService.class); helloSpringService.say(); } }
ClassPathXmlApplicationContext:經過classpath路徑(相對路徑)直接得到加載的xml文件(推薦使用)
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
FileSystemXmlApplicationContext:經過文件路徑(絕對路徑)來得到加載的xml文件。
ApplicationContext context = new FileSystemXmlApplicationContext("D:\\java\\eclipse-workspace\\spring1\\src\\applicationContext.xml");
依賴注入是指Spring建立對象的過程當中,將對象依賴屬性(簡單值,集合,對象)經過配置設值給該對象。
Spring號稱是一個能夠實現模塊可插拔的JavaEE開發框架。而實現程序可插拔的核心理念就是控制反轉。所謂的控制反轉,就是將代碼的調用權從調用方轉移給被調用方(服務提供方)。不用修改調用方的的代碼,只要修改配置文件就實現對象的切換。
讀做「反轉控制」,更好理解,它不是什麼技術,而是一種設計思想,比如於MVC。就是將本來在程序中手動建立對象的控制權,交由Spring框架來管理。
正控:若調用者須要使用某個對象,其自身就得負責該對象的建立。
反控:調用者只管負責從Spring容器中獲取須要使用的對象,不關心對象的建立過程,也就是把建立對象的控制權反轉給了Spring框架。
控制反轉(Ioc),就是依賴注入加上面向接口的編程思想的實現
總體結構:
CustomService接口:
package com.gjs.service; public interface CustomeService { public void say(); }
實現類CustomServiceImpl1:
package com.gjs.service.impl; import com.gjs.service.CustomeService; public class CustomServiceImpl1 implements CustomeService { @Override public void say() { System.out.println("CustomerServiceImpl1.say()"); } }
實現類CustomServiceImpl2:
package com.gjs.service.impl; import com.gjs.service.CustomeService; public class CustomServiceImpl2 implements CustomeService { @Override public void say() { System.out.println("CustomerServiceImpl2.say()"); } }
調用方 CustomClient:
package com.gjs.client; import com.gjs.service.CustomeService; public class CustomClient { //1.聲明一個接口引用類型 private CustomeService customeService; //2.spring的依賴注入(DI)須要有一個set方法 public void setCustomeService(CustomeService customeService) { this.customeService = customeService; } public void say() { customeService.say(); } }
配置文件 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"> <!-- <bean id="" class = ""> 配置讓spring管理類的對象的建立 id : 惟一標識 class :被管理類的全限定名 --> <bean id="client" class="com.gjs.client.CustomClient"> <!-- 依賴注入(DI) :注入被調用方 <property name="" value/ref=""/> 位置: name : 是set方法肯定的屬性,不是成員變量 肯定屬性 : setXxx 方法去掉set前綴 ,剩餘部分首字母小寫 參數: value : 值類型注入(字符串,基本數據類型) ref :引用數據類型(對象), 對應bean的id --> <property name="customeService" ref="ServiceImpl1"/> </bean> <bean id="ServiceImpl1" class="com.gjs.service.impl.CustomServiceImpl1"/> <bean id="ServiceImpl2" class="com.gjs.service.impl.CustomServiceImpl2"/> </beans>
測試類:
package com.gjs.test; import static org.junit.Assert.*; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.gjs.client.CustomClient; import com.gjs.service.CustomeService; public class TestSpring { @Test public void testName() throws Exception { //1.讀取配置文件,建立Spring容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //獲取調用方 CustomClient對象 CustomClient client = context.getBean("client", CustomClient.class); //調用CustomClient對象的say()方法 client.say(); } }
Spring框架又被稱爲容器框架,即經過控制反轉將各個框架的對象建立交給Spring管理,而後經過依賴注入在層之間傳遞參數整合框架,並達到低耦合的目的。
做用:用於聲明一個類,在啓動Spring框架的時候根據該配置的類建立對象到容器裏面
<bean id="someBean" class="com.gjs.pojo.SomeBean" scope="prototype"></bean>
id:設置對象名(惟一標識符)(推薦使用)
name:設置對象名(惟一標識符),與id的區別是能夠有多個名稱,每一個名稱用逗號隔開。
class:指定對象對應的類
scope:用於設置的對象的做用範圍,可選參數以下:
在Web開發的三層架構中的使用
Web層:通常都是多例
Service層 :單例
DAO層 :單例
做用:爲已配置的bean設置別名
bean id="user" name="test" class="com.gjs.pojo.User"/>
<alias name="user" alias="user1"/>
name:必要屬性, 表明爲哪個bean配置別名, 此屬性的值爲其餘bean標籤的id或name屬性值
alias: 必要屬性,命名的別名
1.構造器實例化(無參數構造器):(最經常使用)
public class SomeBean { public SomeBean() { System.out.println("SomeBean.SomeBean()"); } }
<bean id="someBean" class="com.gjs.pojo.SomeBean"/>
2.經過靜態方法工廠建立(C)
public class SomeBean { public SomeBean() { System.out.println("SomeBean.SomeBean()"); } } public class SomeBeanFacotry { //靜態工廠方法 public static SomeBean getSomeBean() { System.out.println("執行靜態工廠方法"); return new SomeBean(); } }
<bean id="someBean" class="com.gjs.pojo.SomeBeanFacotry" factory-method="getSomeBean"/>
3.經過實體工廠建立(C)
public class SomeBean { public SomeBean() { System.out.println("SomeBean.SomeBean()"); } } public class SomeBeanFacotry { //實例工廠方法 public SomeBean getSomeBean() { System.out.println("執行實例工廠方法"); return new SomeBean(); } }
<bean id="someBeanfactory" class="com.gjs.pojo.SomeBeanFactory"/>
或
<bean id="someBean" factory-bean="someBeanfactory" factory-method="getSomeBean"/>
4.實現FactoryBean接口實例化:實例工廠變種
實現FactoryBean接口,MyBatis和Spring集成就是使用的這種方式。此種方式,若是沒有使用Bean對應的對象,Spring就不會自動建立,只有在使用的時候Spring纔會建立對應的對象
public class SomeBean { public SomeBean() { System.out.println("SomeBean4.SomeBean4()"); } } public class SomeBeanObjectFactory implements FactoryBean<SomeBean>{ //返回的泛型類型對應的對象 @Override public SomeBean getObject() throws Exception { SomeBean bean = new SomeBean(); return bean; } }
<bean id="someBean" class="cn.zj.domian.SomeBeanObjectFactory"/>
<bean id="someBean" class="......"
<init-method="該類中初始化方法名"/>
<destroy-method="該類中銷燬方法名"/>
</bean>
init-method:bean生命週期初始化方法,對象建立後就進行調用
destroy-method:容器被銷燬的時候,若是bean被容器管理,會調用該方法。
1.setter注入,(屬性注入)(經常使用)
使用setter注入:
1,使用bean元素的<property>子元素設置;
1.簡單類型值,直接使用value賦值;
2.引用類型,使用ref賦值;
3.集合類型,直接使用對應的集合類型元素便可。
2,spring經過屬性的set方法注入值;
3,在配置文件中配置的值都是string,spring能夠自動的完成類型的轉換
示例:
員工類
public class Employee { private Integer age; private String name; private Department dept; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDept() { return dept; } public void setDept(Department dept) { this.dept = dept; } @Override public String toString() { return "Employee [age=" + age + ", name=" + name + ", dept=" + dept + "]"; } }
部門類
public class Department { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
配置文件
<?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"> <!-- 員工 --> <bean id="employee" class="com.gjs.pojo.Employee" > <!-- setter方法注入: 屬性注入 <property name="" value=""> name : 屬性名稱 value : 基本數據類型+String類型的值注入 ref : 引用類型(對象類型)的注入 value 和ref 只能二選一 --> <property name="age" value="18"></property> <property name="name" value="張三"></property> <property name="dept" ref="dept"></property> </bean> <!-- 部門 --> <bean id="dept" class="com.gjs.pojo.Department" > <property name="id" value="1"/> <property name="name" value="開發部"/> </bean> </beans>
2.構造器注入
使用bean元素的<constructor-arg>子元素設置:
1.默認狀況下,constructor-arg的順序就是構造器參數的順序
2. constructor-arg的屬性
name : 構造方法參數的名稱
index :參數的位置從 0 開始
value :值類型注入
ref :引用類型注入
type : 參數的數據類型
3.通常在一個類必須依賴另外一個類才能正常運行時,才用構造器注入
<?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"> <!-- 配置部門 --> <bean id="department" class="com.gjs.pojo.Department"> <constructor-arg name="id" value="2"/> <constructor-arg name="name" value="研發部"/> </bean> <!-- 配置員工 --> <bean id="emp" class="com.gjs.pojo.Employee"> <!-- 依賴注入 :構造器注入 --> <constructor-arg name="id" value="1"/> <constructor-arg name="name" value="張三"/> <constructor-arg name="dept" ref="department"/> </bean> </beans>
3.p命名空間注入
使用p命名空間注入先在約束上面引入 p標籤
xmlns:p="http://www.springframework.org/schema/p"
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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"> <!-- 配置部門 --> <bean id="department" class="com.gjs.pojo.Department" p:id="3" p:name="銷售部"/> <!-- 配置員工 --> <bean id="emp" class="com.gjs.pojo.Employee" p:id="1" p:name="張三" p:dept-ref="department"/> </beans>
4.集合類型值注入
用於處理:
1.鍵值對 Map 、Properties
2.數組
3.集合Set、List
public class CollectionBean { private Set<String> set; private List<String> list; private String[] array; private Map<String, String> map; private Properties prop; //讀取本地 xxx.properties文件(本質就是一個Map集合) }
<?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"> <bean id="collectionBean" class="cn.zj.spring.pojo.CollectionBean"> <!-- setter(屬性)方法注入 --> <!-- 1.數組 --> <property name="arr"> <array> <value>AAA</value> <value>BBB</value> </array> </property> <!-- 2.set集合 --> <property name="set" > <set> <value>AAA</value> <value>AAA</value> <value>BBB</value> </set> </property> <!-- 3.list集合 --> <property name="lsit"> <list> <value>list1</value> <value>list1</value> <value>list2</value> </list> </property> <!-- 4. map集合 --> <property name="map"> <map> <entry key="key1" value="value1"/> <entry key="key2" value="value2"/> </map> </property> <!-- 5.properties 集合 --> <property name="prop"> <props> <prop key="propKey1">propValue1</prop> <prop key="propKey2">propValue2</prop> </props> </property> </bean> </beans>
1.導入命名空間方法
將命名空間和約束從新拷貝一份,將對於的所有替換成 context,而後關聯context本地schema約束
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> </beans>
2.導入Mysql驅動包和druid鏈接池jar包
3.applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 使用context 讀取配置文件到spring容器中 <context:property-placeholder location=""/> location : db.properties文件的位置,必須加上 classpath: 做爲前綴 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 建立阿里巴巴druid鏈接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close" > <!-- 屬性注入 setter方法注入--> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 最大鏈接數 --> <property name="maxActive" value="${jdbc.maxActive}"/> </bean> </beans>
測試代碼
@Test public void testSave() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = context.getBean(DataSource.class, "dataSource"); Connection conn = dataSource.getConnection(); System.out.println("數據庫鏈接對象:"+conn); }