Spring Framework
依賴注入、事務管理、Web應用程序、數據訪問、消息傳遞、測試和更多的核心支持。
Tips:
Spring 官網:https://spring.io/
spring framework 官網:https://projects.spring.io/spring-framework/
0x01介紹
Spring框架提供了現代的基於java的企業應用程序在任何部署平台的綜合規划和配置模型。Spring的一個關鍵元素是應用程序級的基礎設施支持:Spring關注企業應用程序的“管道”,以便團隊能夠專注於應用級業務邏輯,而不必與特定部署環境不必要的聯系。
0x02 功能
- 核心技術:依賴注入、事件、資源、國際化、驗證、數據綁定、類型轉換,拼寫,AOP。
- 測試:模擬對象,TestContext框架,Spring MVC測試,WebTestClient。
- 數據訪問:事務、DAO支持、JDBC、ORM、編組XML。
- Spring MVC Web框架和 Spring WebFlux web 框架
- 整合:Remoting、JMS、JCA、JMX、電子郵件、任務調度、緩存。
- 語言:Kotlin,Groovy動態語言。
0x03 Minimum requirements
- JDK 8+ for Spring Framework 5.x
- JDK 6+ for Spring Framework 4.x
- JDK 5+ for Spring Framework 3.x
0x04 Building Java Projects with Maven
和大多數 Spring入門指南 一樣,您可以從頭開始完成每一步,也可以繞過您已經熟悉的基本設置步驟。無論哪種方式,最終都有工作代碼。
- 1. 手動使用Maven創建Java 項目
2. 勾選如圖所示兩個地方
3. 填寫Project Name,點擊 ’Finish‘ 按鈕
4. 創建hello 文件夾,目錄結構如圖所示:
5. 修改POM.xml 文件內容如下所示:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xingyun</groupId> <artifactId>spring-context-sample</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- 添加Spring Context maven依賴 --> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.4.RELEASE</version> </dependency> </dependencies> </project>
6.創建接口文件
hello/MessageService.java
package hello; public interface MessageService { String getMessage(); }
7.創建實體類
hello/MessagePrinter.java
package hello; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MessagePrinter { final private MessageService service; @Autowired public MessagePrinter(MessageService service) { this.service = service; } public void printMessage() { System.out.println(this.service.getMessage()); } }
Tips:這里一定不要漏了寫這兩個注解
8.創建方法調用主類
hello/Application.java
package hello; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; @Configuration @ComponentScan public class Application { @Bean MessageService mockMessageService() { return new MessageService() { public String getMessage() { return "Hello World!"; } }; } public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new AnnotationConfigApplicationContext(Application.class); MessagePrinter printer = context.getBean(MessagePrinter.class); printer.printMessage(); } }
Tips:這里特別注意,任何一個注解都不能缺少,否則會報錯。
9. Run 主方法
上面的例子顯示了依賴注入的基本概念,messageprinter 實現 MessageService接口是解耦的,寫什么都可以使用Spring Framework。
本文項目源碼下載地址:https://github.com/geekxingyun/JavaEE-Framework-Sample/tree/master/SpringBoot-Sample/spring-context-sample
0x05 其他更多用法參考文檔