一、spring 框架概念
spring 是眾多開源 java 項目中的一員,基於分層的 javaEE 應用一站式輕量
級開源框架,主要核心是 Ioc(控制反轉/依賴注入) 與 Aop(面向切面)兩大技
術,實現項目在開發過程中的輕松解耦,提高項目的開發效率。
在項目中引入Spring可以帶來以下好處:
1.降低組件之間的耦合度,實現軟件各層之間的解耦。
2.可以使用容器提供的眾多服務,如:事務管理服務、消息服務等等。
3.當我們使用容器管理事務時,開發人員就不再需要手工控制事務.也不需處理復
雜的事務傳播。
4.容器提供單例模式支持,開發人員不再需要自己編寫實現代碼。
5.容器提供了 AOP 技術,利用它很容易實現如權限攔截、運行期監控等功能。
二、Spring 源碼架構
Spring 總共大約有 20 個模塊, 由 1300 多個不同的文件構成。 而這些組件被分別整合在核心容器(Core Container) 、 Aop(Aspect OrientedProgramming) 和設備支持(Instrmentation) 、 數據訪問及集成(DataAccess/Integeration) 、Web、 報文發送(Messaging) 、 測試 6 個模塊集合中。
三、Spring 框架環境搭建
1.maven 創建普通 java 工程並調整整體工程環境
2.坐標 依賴添加 spring 框架核心坐標添加
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.9.RELEASE</version> </dependency>
- 1
- 2
- 3
- 4
- 5
3.編寫 bean
package com.shsxt.service;
public class HelloService { public void hello(){ System.out.println("hello spring"); } }
4.spring 配置文件的編寫
在 src 下新建 xml 文件,並拷貝官網文檔提供的模板內容到 xml 中,配置bean 到 xml 中,把對應 bean 納入到 spring 容器來管理
<?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 即 xml namespace xml 使用的命名空間 xmlns:xsi 即 xml schema instance xml 遵守的具體規范 xsi:schemaLocation 本文檔 xml 遵守的規范 官方指定 --> <bean id="helloService" class="com.shsxt.service.HelloService"></bean> </beans>
5.驗證 spring 框架環境是否搭建成功
package com.shsxt.service; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloServiceTest { @Test public void test1() throws Exception { /** * 1.加載Spring的配置文件 * 2.取出Bean容器中的實例 * 3.調用bean方法 */ // 1.加載Spring的配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); // 2.取出Bean容器中的實例 HelloService helloService = (HelloService) context.getBean("helloService"); // 3.調用bean方法 helloService.hello(); } }