簡單記錄一下學習內容
首先貼上官網鏈接 https://spring.io/
使用的平臺是 intellij idea
先是概念性的東西,簡單概述一下 spring 框架的內容
Spring 是一個非常活躍的開源框架,幫助公司分離項目組件之間的關係。
Spring 有以下幾大特點:
IOC -- inversion of control 控制反轉
簡單的來說就是創建對象和對象之間的依賴維護 控制權由程序員變成了 Spring(託管)。
DI -- dependec of injection 依賴注入就是 spring 對象之間依賴關係的創建。 可以通過 annotation 和 xml 兩種方式實現。
AOP -- aspect oriented programming
面向切面編程(目前不是很懂)
幾大核心塊
Core containner
core: IOC DI
beans: 創建對象的工廠
Context: IOC容器, 其實就是 Spring 容器
SpEL:Spring 表達語言
Data access:
JDBC: 你懂得
ORM:對象關係映射
OXM: 對象和xml轉換
JMS:生產消費
Transcations:事務管理
Web:
面向web 應用程序
portlet 首頁的窗口
Spring 包含 Spring MVC
快速創建流程
在 ideallij 中用 maven 方式創建新工程,在 pom 中添加依賴, 在 artifacrt-id 中輸入 spring-context 會自動生成相關文件,點擊 import 即可。
當然,你直接創建 Spring 工程文件也行。
不同的 Spring 容器使用方法
註釋方式
@Component 寫在類前面,使得當前類在未來創建對象時不需要 new 關鍵字。
@ComponentScan 一般用於主程序,會掃描所有的 @Component 。
ApplicationContext context = new AnnotationConfigApplicationContext();
這一句話會創建所有有相關注釋的類的實例,並把其放在 Spring 容器中。
AnnotationConfigApplicationContext() 括號中的內容是 Spring 容器(主程序)所在位置(@ComponentScan 所在位置)比如 application.class。
MessagePrinter printer = context.getBean(MessagePrinter.class);
通過特定類可以從容器中獲取到實例。
@Autowired
寫在方法前,被其註釋的方法會在實例創建時自動調用。比如我需要傳一個 service 對象給 printer 才能完成 setter 的操作,但如果加上這個會自動 創建並且調用 setter。
這個之後會再單獨陳述。
XML 方式
<!--
bean元素表示當前元素需要 spring 容器管理
id 屬性 標識對象 未來在應用程序中通過id 獲取對象
class 被管理對象的類的全名
-->
<bean id="service" class="hello.MessageService"></bean>
<bean id="printer" class="hello.MessagePrinter">
(// 依賴,name 指類下面的對象名 ref 指 id 這句話不要複製進去)
<property name="service" ref="service"></property>
</bean>
雖然不用任何註釋了,上面的獲取容器方法的語句要重新寫過。
ApplicationContext context = new ClassPathXmlApplicationContext("application_context.xml");
引入log4j2
添加依賴
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>
在 res 下創建 log4j2.properties
輸入以下文字
status = warn
name = MyApp
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %m%n
appender.rolling.type = File
appender.rolling.name = log
appender.rolling.append = true
appender.rolling.fileName = e:\\test1.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d-%m%n
rootLogger.level = debug
rootLogger.appenderRef.stdout.ref = STDOUT
rootLogger.appenderRef.log.ref = log
再次運行就能看到全部過程了!
P.S.
ideallij 裏面的幾個快捷鍵
sout 打印
ctrl + o 快速創建構造方法(第一個 object())
alt + insert 可以自動生成 setter 方法
ctrl+ space 快速填充