JavaWeb-初識Spring

来源:https://www.cnblogs.com/coderaji/archive/2023/10/21/17779312.html
-Advertisement-
Play Games

目錄 Spring簡介 Spring項目 Bean管理 基於xml的Bean管理 創建對象 屬性註入 基於xml+註解的Bean管理 創建對象 屬性註入 基於純註解的Bean管理 內容 Spring簡介 Spring是什麼 Spring是於2003 年興起的一個輕量級的Java的開放源代碼的設計層面 ...


目錄

  1. Spring簡介

  2. Spring項目

  3. Bean管理

    1. 基於xml的Bean管理

    2. 基於xml+註解的Bean管理

    3. 基於純註解的Bean管理

內容

Spring簡介

  1. Spring是什麼

    Spring是於2003 年興起的一個輕量級的Java的開放源代碼的設計層面框架。Spring解決的是業務邏輯層和其他各層的松耦合問題,因此它將面向介面的編程思想貫穿整個系統應用。

  2. Spring核心是什麼

    Spring的核心是控制反轉(IOC)和麵向切麵(AOP)。

    1. IOC:控制反轉,將創建對象的過程交給spring進行管理。

    2. AOP:面向切麵,在不修改源代碼的情況之下進行代碼功能的增強。

  3. Spring優勢是什麼

    Spring是為瞭解決企業應用開發的複雜性而創建的。Spring框架的主要優勢之一就是其分層架構,分層架構允許使用者選擇使用哪一個組件,同時為 JavaEE 應用程式開發提供集成的框架。總結下來分以下幾點:

    1. 方便解耦,簡化開發,Spring就是一個大工廠,可以將所有對象創建和依賴關係維護,交給Spring管理,這也是IOC的作用。

    2. AOP編程的支持,Spring提供面向切麵編程,可以方便的實現對程式進行許可權攔截、運行監控等功能。

    3. 聲明式事務的支持,只需要通過配置就可以完成對事務的管理,而無需手動編程。

    4. 方便程式的測試,Spring對Junit4支持,可以通過註解方便的測試Spring程式。

    5. 方便集成各種優秀框架,Spring不排斥各種優秀的開源框架,其內部提供了對各種優秀框架(如:Struts2、Hibernate、MyBatis等)的直接支持。

    6. 降低JavaEE API的使用難度,Spring 對JavaEE開發中非常難用的一些API(JDBC、JavaMail等),都提供了封裝,使這些API應用難度大大降低。

  4. Bean是什麼

    Bean是Spring容器管理的對象。

  5. Spring容器是什麼

    Spring容器是創建以及管理Bean對象的。

Spring項目

  1. IDEA創建項目

  2. 配置Maven,使用預設版本也可以

  3. 導入spring和單元測試junit依賴

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    

  4. 創建spring-config.xml(文件名隨便取)

Bean管理

  1. 創建Demo類

    public class Demo {
        private String name;
        private Integer age;
        public Demo(){}
        public Demo(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
        public void setName(String name) {this.name = name;}
        public void setAge(Integer age) {this.age = age;}
        @Override
        public String toString() {
            return "Demo{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

  2. 創建測試類

    import org.junit.Test;
    
    public class Main {
        @Test
        public void test(){
    
        }
    }
    

基於xml的Bean管理

創建對象
  1. spring配置文件(spring-config.xml)添加配置,註冊Demo類為Bean對象

    <bean class="com.example.aji.bean.Demo" id="demo">
    
    </bean>
    

  2. 從容器中取出Demo對象

    • ApplicationContext spring上下文

    • ClassPathXmlApplicationContext 以xml配置文件方式創建上下文

    • .getBean(beanName) 跟據beanName從上下文中獲取Bean對象

    • .getBean(class) 跟據class從上下文中獲取Bean對象

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        Demo demo = (Demo)context.getBean("demo");
        System.out.println(demo);
    }
    

屬性註入
  1. 構造器註入

    • constructor-arg 通過構造器註入屬性
    <bean class="com.example.aji.bean.Demo" id="demo">
        <constructor-arg name="name" value="aji"/>
        <constructor-arg name="age" value="20"/>
    </bean>  
    

  2. set方法註入

    • property 通過set方法註入屬性
    <bean class="com.example.aji.bean.Demo" id="demo">
        <property name="name" value="aji"/>
        <property name="age" value="21"/>
    </bean> 
    

基於xml+註解的Bean管理

  1. 註解

    • 註解是代碼特殊標記,格式:@註解名稱(屬性名稱=屬性值,屬性名稱=屬性值...)

    • 使用註解,註解作用在類上面,方法上面,屬性上邊

    • 使用註解的目的:簡化XML配置

  2. 編輯Spring配置文件添加註解掃描功能

    <!--開啟註解掃描 com.example.aji 所有的包中的所有的類-->
    <context:component-scan base-package="com.example.aji"/>
    

創建對象
  1. Spring針對Bean管理中創建對象提供的註解

    • @Component 普通的類

    • @Controller 表現層

    • @Service 業務層

    • @Repository 持久層

  2. 創建普通對象

    import org.springframework.stereotype.Component;
    @Component
    public class Demo {
        private String name;
        private Integer age;
        public Demo(){}
        public Demo(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public String toString() {
            return "Demo{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

  3. 創建業務層對象

    • 創建DemoService介面

      public interface DemoService {
          Demo getDemo();
      }
      
    • 創建DemoServiceImpl實現DemoService介面變更添加

      import com.example.aji.bean.Demo;
      import com.example.aji.service.DemoService;
      import org.springframework.stereotype.Service;
      
      @Service(value = "demoService")
      public class DemoServiceImpl implements DemoService {
          @Override
          public Demo getDemo() {
              return new Demo("aji",20);
          }
      }
      

  4. 其他對象也類似,添加相應註解即可

屬性註入
  1. 屬性註入註解

    • @Value 用於註入普通類型(String,int,double等類型)

    • @Autowired 預設按類型進行自動裝配(引用類型)

    • @Qualifier 不能單獨使用必須和@Autowired一起使用,強制使用名稱註入

    • @Resource Java提供的註解,也被支持。使用name屬性,按名稱註入

  2. @Value

    @Component
    public class Demo {
        @Value("aji")
        private String name;
        @Value(value = "21")
        private Integer age;
    
        @Override
        public String toString() {
            return "Demo{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

  3. @Autowired

    import com.example.aji.bean.Demo;
    import com.example.aji.service.DemoService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service(value = "demoService")
    public class DemoServiceImpl implements DemoService {
        @Autowired
        private Demo demo;
    
        @Override
        public Demo getDemo() {
            return demo;
        }
    }
    

基於純註解的Bean管理

  1. 刪除spring-config.xml文件,並創建SpringConfig類,添加@Component註解把該類交給spring處理,添加@ComponentScan註解指定spring掃描的包路徑

    @Component
    @ComponentScan("com.example.aji")
    public class SpringConfig {
    }
    

  2. 測試(其餘部分與xml+註解方式一致)

    @Test
    public void test(){
        //ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        /*Demo demo = (Demo)context.getBean("demo");
        System.out.println(demo);*/
        DemoService demoService = (DemoService)context.getBean("demoService");
        System.out.println(demoService.getDemo());
    }
    


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 先拋一下結論:在滿足實時性的條件下,不存在兩者完全保存一致的方案,只有最終一致性方案。根據網上的眾多解決方案,總結出 6 種,直接看目錄: 不好的方案 1、先寫 MySQL,再寫 Redis 如圖所示: 這是一副時序圖,描述請求的先後調用順序; 橘黃色的線是請求 A,黑色的線是請求 B; 橘黃色的文 ...
  • 複習css 樣式 內聯樣式,行內樣式,外部樣式優先順序 離HTML元素越近,優先順序越高 內聯樣式離元素近:行內樣式>內聯樣式>外部樣式 外部樣式離元素近:行內樣式>外部樣式>內斂樣式 本質:瀏覽器從上到下解析過程中,後出現的樣式會覆蓋較早出現的樣式 選擇器 基本選擇器 id > 類 > 標簽 本質:定 ...
  • 算術運算符簡表 運算符 描述 例子 x的運算結果 y的運算結果 線上實例(來源runoob.com) + 加法 x=y+2 7 5 實例>> - 減法 x=y-2 3 5 實例>> * 乘法 x=y*2 10 5 實例>> / 除法 x=y/2 2.5 5 實例>> % 取餘數(模) x=y%2 1 ...
  • 這幾天學習智能指針時,自己在練習寫個管理數組指針的類時碰到了通過數組指針獲取數組個數的問題 1.在網上查詢了通過數組指針獲取數組個數的方法,對於自定義數據在前四個節點保存了數組個數 Student* pAry = new Student[3]; size_t num = *((size_t*)pAr ...
  • 隨著互聯網的發展,越來越多的應用和服務需要通過API介面來實現。API(Application Programming Interface,應用程式編程介面)可以理解為兩個軟體之間的橋梁,通過API介面,兩個軟體可以相互交流併進行數據交換。如今,API已經成為許多公司和應用程式的核心,因此快速搭建並 ...
  • 源起: 使用python分離出一串文本,因為是看起來像整數,結果json轉換時發生異常:TypeError: Object of type Decimal is not JSON serializable msgInfo={"uid":3232324232} json.dumps(msgInfo, ...
  • 通過前面13天的學習,對Dart基礎有了系統的熟悉,今天我們開始學習Dart類和對象,本文主要學習Dart類,包括類方法,構造器,對象類型,實例變數,隱性介面,類變數和類方法等…… ...
  • Python有兩個基本的迴圈命令: while迴圈 for迴圈 while迴圈 使用while迴圈,我們可以在條件為真的情況下執行一組語句。 示例,列印i,只要i小於6: i = 1 while i < 6: print(i) i += 1 註意:記得增加i的值,否則迴圈將永遠繼續下去。 while ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...