Spring基本認識和入門使用超詳細教程
Spring

spring概述
1 Spring定義
? Spring是一款主流的Java EE 輕量級開源框架,目的是用于簡化Java企業(yè)級引用的開發(fā)難度和開發(fā)周期。從簡單性、可測試性和松耦合度的角度而言,任何Java應(yīng)用都可以從Spring中受益。Spring框架提供自己提供功能外,還提供整合其他技術(shù)和框架的能力。
? Spring自誕生以來備受青睞,一直被廣大開發(fā)人員作為Java企業(yè)級應(yīng)用程序開發(fā)的首選。時至今日,Spring儼然成為了Java EE的代名詞,成為了構(gòu)建Java EE 應(yīng)用的事實標準。
? 自2004年4月,Spring1.0 版正式發(fā)布以來,Spring已經(jīng)步入到了第6個大版本,即 Spring6,以下內(nèi)容采用Spring5.3.24正式版本。

2 Spring核心
? Spring指的是Spring Framework,通常我們稱之為Spring框架。Spring框架是一個分層的面向切面的Java應(yīng)用程序的一站式解決框架,它是Spring技術(shù)棧的核心和基礎(chǔ),是為了解決企業(yè)級引用開發(fā)的復(fù)雜性而創(chuàng)建的。
? Spring有兩個核心模塊:IoC和AOP。
? Ioc:Inverse of Control的簡寫,為 控制反轉(zhuǎn),指把創(chuàng)建對象交給Spring進行管理。
? AOP:Aspect Oriented Programming 的簡寫,為 面向切面編程。AOP用來封裝多個類的公共行為,將那些與業(yè)務(wù)無關(guān),卻為業(yè)務(wù)模塊共同調(diào)用的邏輯封裝起來,減少系統(tǒng)的重復(fù)代碼,降低模塊間的耦合度。另外,AOP還解決一些系統(tǒng)層面上的問題,比如日志、事務(wù)、權(quán)限等。
3 Spring Framework的特點
- 控制反轉(zhuǎn):IoC,反轉(zhuǎn)資源獲取方向;把自己創(chuàng)建的資源、向環(huán)境索取資源變?yōu)榄h(huán)境將資源準備好,我們享受資源注入。
- 面向切面編程:AOP,在不修改源代碼的基礎(chǔ)上增強代碼功能。
- 容器:Spring IoC是一個容器,因為它包含并管理組件對象的生命周期;組件享受到了容器化的管理,替程序員屏蔽了組件創(chuàng)建過程中的大量細節(jié),極大降低了使用門檻,大幅度提高了開發(fā)效率。
- 一站式:在IOC和AOP的基礎(chǔ)上可以整合各種企業(yè)應(yīng)用的開源框架和優(yōu)秀的第三方庫,而且在Spring旗下的項目已經(jīng)覆蓋了廣泛領(lǐng)域,很多方面的功能性需求可以在Spring Framework 的基礎(chǔ)上全部使用Spring來實現(xiàn)。
入門案例
1 環(huán)境要求
- JDK:Java8-15
- Spring:5.3.24
2 構(gòu)建工程
2.1 構(gòu)建子工程first-spring
? 在jsd2303-spring中創(chuàng)建子工程 spring-first
New - Module

點擊 Next

Name為spring-first,點擊 Finish

2.2 入門案例
① 在spring-first/pom.xml中引入相關(guān)依賴,并 刷新maven
<dependencies>
<!-- spring context依賴
當引入此依賴后,表示將Spring的基礎(chǔ)依賴引入了
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
</dependencies>② 在工程中創(chuàng)建包 cn.tedu.spring.begin

③ 創(chuàng)建類 User

④ User類中定義方法
public class User {
public void add(){
System.out.println("添加方法...");
}
}⑤ 創(chuàng)建spring配置文件:resources目錄下創(chuàng)建bean.xml



⑥ 在bean.xml中用標簽完成對象創(chuàng)建
<?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">
<!--完成user對象創(chuàng)建
id屬性:唯一標識
class屬性:要創(chuàng)建的對象所在類的絕對路徑
-->
<bean id="user" class="cn.tedu.spring.User"></bean>
</beans>⑦ 創(chuàng)建測試類cn.tedu.spring.TestUser進行測試
public class TestUser {
public static void main(String[] args) {
// 1.加載spring配置文件,進行對象創(chuàng)建
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
// 2.獲取spring創(chuàng)建好的對象
User user = (User) context.getBean("user");
// 3.使用對象調(diào)用方法測試
System.out.println("user = " + user);
user.add();
}
}2.3 對象存儲
存放到容器中,查看源碼,DefaultListableBeanFactory.java,第164行

key:唯一標識
value:類的定義(描述信息)
可以查看 BeanDefinition 的源碼,有類的描述信息,是否初始化的狀態(tài)等等
IoC容器
? IoC 是 Inversion of Control 的簡寫,譯為 控制反轉(zhuǎn)。
? Spring通過IoC容器來管理所有的Java對象的實例化和初始化,控制著對象與對象之間的依賴關(guān)系。我們將由IoC容器管理的Java對象成為 Spring Bean,它與使用關(guān)鍵字 new 創(chuàng)建的Java對象沒有任何區(qū)別。
? IoC容器是Spring框架中最重要的核心組件之一,它貫穿了Spring從誕生到成長的整個過程。
1 控制反轉(zhuǎn)IoC
- 控制反轉(zhuǎn)是一種思想
- 將對象的創(chuàng)建權(quán)利交出去,交給第三方容器負責(zé)
- 將對象和對象之間的關(guān)系維護權(quán)交出去,交給第三方容器負責(zé)
- 如何實現(xiàn)
- 通過依賴注入DI的方式實現(xiàn)
2 依賴注入DI
DI (Dependency Injection):依賴注入,依賴注入實現(xiàn)了控制反轉(zhuǎn)的思想,是指Spring創(chuàng)建對象的過程中,將對象依賴屬性通過配置進行注入。
依賴注入常見的實現(xiàn)方式有兩種:
- set注入
- 構(gòu)造注入
所以 IoC 是一種控制反轉(zhuǎn)的思想,而 DI 是對IoC的一種具體實現(xiàn)。
Bean管理:指Bean對象的創(chuàng)建,以及Bean對象中屬性的賦值(或Bean對象之間關(guān)系的維護)
3 IoC容器實現(xiàn)
Spring中的IoC容器就是IoC思想的一個落地產(chǎn)品實現(xiàn)。IoC容器中管理的組件也叫做bean。在創(chuàng)建bean之前,首先需要創(chuàng)建IoC容器,Spring提供了IoC容器的兩種實現(xiàn)方式
① BeanFactory
? 這是IoC容器的基本實現(xiàn),是Spring內(nèi)部使用的接口。面向Spring本身,不提供給開發(fā)人員使用。
② ApplicationContext
? BeanFactory的子接口,提供了更多高級特性,面向Spring的使用者,幾乎所有場合都使用 ApplicationContext,而不是底層的BeanFactory
源碼說明:

③ ApplicationContext的主要實現(xiàn)類
| 類型 | 說明 |
|---|---|
| ClassPathXmlApplicationContext | 通過讀取類路徑下的xml格式配置文件創(chuàng)建IoC容器對象 |
| FileSystemApplicationContext | 通過文件系統(tǒng)路徑讀取xml格式配置文件創(chuàng)建IoC容器對象 |
4 基于XML管理bean
4.1 環(huán)境準備
① 創(chuàng)建子工程 spring-ioc-xml

② pom.xml中引入spring依賴,并刷新maven
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
</dependencies>③ 創(chuàng)建spring配置文件:resources/bean.xml

④ 在工程目錄java下創(chuàng)建類 cn.tedu.spring.iocxml.User
public class User {
private String username;
private String password;
public void userMethod(){
System.out.println("userMethod執(zhí)行~~");
}
}4.2 獲取bean方式
根據(jù)id獲取
id屬性是bean的唯一標識,所以根據(jù)bean標簽的id屬性可以精確獲取到一個組件對象。
① bean.xml
<bean id="user" class="cn.tedu.spring.iocxml.User"></bean>
② 創(chuàng)建測試類UserTest
public class UserTest {
public static void main(String[] args) {
// 1.加載配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
// 2.根據(jù)id獲取bean
User user1 = (User) context.getBean("user");
System.out.println("1-根據(jù)id獲取對象:" + user1);
user1.userMethod();
}
}根據(jù)類型獲取
User user2 = context.getBean(User.class);
System.out.println("2-根據(jù)類型獲取bean:" + user2);
user2.userMethod();
根據(jù)id和類型獲取
User user3 = context.getBean("user", User.class);
System.out.println("3-根據(jù)id和類型獲取bean:" + user3);
user3.userMethod();
注意
當根據(jù)類型獲取bean時,要求IoC容器中指定類型的bean只能有一個,當配置兩個時會拋出異常
<bean id="user" class="cn.tedu.spring.iocxml.User"></bean> <bean id="user2" class="cn.tedu.spring.iocxml.User"></bean>

4.3 基于setter依賴注入
類有屬性,創(chuàng)建對象過程中,向?qū)傩宰⑷刖唧w的值
方式1:使用set方法完成(使用xml中的標簽實現(xiàn))
方式2:基于構(gòu)造器完成
案例
① 創(chuàng)建Package名為dibase,創(chuàng)建Book類
package cn.tedu.spring.DI;
public class Book {
private String bookName;
private String bookAuthor;
// 無參構(gòu)造函數(shù)
public Book() {}
// 全參構(gòu)造函數(shù)
public Book(String bookName, String bookAuthor) {
this.bookName = bookName;
this.bookAuthor = bookAuthor;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookAuthor() {
return bookAuthor;
}
public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
}
@Override
public String toString() {
return "Book{" +
"bookName='" + bookName + '\'' +
", bookAuthor='" + bookAuthor + '\'' +
'}';
}
}② 創(chuàng)建spring配置文件:resources目錄下創(chuàng)建 bean-di.xml
<!-- set方法注入 -->
<bean id="book" class="cn.tedu.spring.DI.Book">
<!--2.使用property標簽注入-->
<property name="bookName" value="java"></property>
<property name="bookAuthor" value="tedu"></property>
</bean>③ 創(chuàng)建測試類TestBook進行測試
public class BookTest {
// spring的set方法注入
@Test
public void springSetTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-di.xml");
Book book = context.getBean("book", Book.class);
System.out.println("book = " + book);
}
}4.4 基于構(gòu)造器依賴注入
- 說明
- 通過構(gòu)造器方式實現(xiàn)依賴注入
- 操作步驟說明
- 創(chuàng)建類,定義屬性,生成有參數(shù)構(gòu)造方法
- 進行xml配置
- 創(chuàng)建測試類測試
① 創(chuàng)建電影信息類Film,定義屬性并生成全參構(gòu)造方法
public class Film {
// 電影名稱、主演
private String title;
private String actor;
// 全參構(gòu)造
public Film(String title, String actor) {
System.out.println("Film的有參構(gòu)造已經(jīng)執(zhí)行~~");
this.title = title;
this.actor = actor;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
@Override
public String toString() {
return "Film{" +
"title='" + title + '\'' +
", actor='" + actor + '\'' +
'}';
}
}② 在bean-di.xml中進行注入配置
<!-- 構(gòu)造器注入演示:Film類 -->
<bean id="film" class="cn.tedu.spring.DI.Film">
<constructor-arg name="title" value="霸王別姬"></constructor-arg>
<constructor-arg name="actor" value="張國榮"></constructor-arg>
</bean>③ 創(chuàng)建測試類TestFilm測試
public class FilmTest {
@Test
public void FilmConsDITest(){
// 1.加載配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean-di.xml");
// 2.獲取指定bean
Film film = context.getBean("film", Film.class);
// 3.輸出測試
System.out.println("film = " + film);
}
}4.5 特殊值處理注入
4.5.1 字面量賦值
string number = 10;
聲明一個變量number,初始化為 10,此時number就不代表字符number了,而是作為一個變量的名字。當引用number時,實際拿到的結(jié)果是 10。
而如果number是帶引號的 “number” ,則它不是一個變量,而代表 number 本身這個字符串。
這就是字面量,所以字面量沒有引申含義,就是我們看到的這個數(shù)據(jù)本身。
<!-- 使用value屬性給bean的屬性賦值時,spring會把value的屬性值看作是字面量 --> <property name="number" value="1016"></property>
4.5.2 null值
使用 標簽,或者 標簽 實現(xiàn)注入。
① Film類中增加電影描述屬性
// 1.電影描述 private String description; // 2.生成對應(yīng)的 set() get() 方法,重新生成toString()方法 // 3.重新生成全參構(gòu)造方法
② bean-di.xml配置文件調(diào)整
<!-- 構(gòu)造器注入演示:Film類 -->
<bean id="film" class="cn.tedu.spring.DI.Film">
<constructor-arg name="title" value="霸王別姬"></constructor-arg>
<constructor-arg name="actor" value="張國榮"></constructor-arg>
<!-- 電影描述注入空值null -->
<constructor-arg name="description">
<null></null>
</constructor-arg>
</bean>③ 執(zhí)行測試類進行測試
- 課堂練習(xí)
- cn.tedu.spring下創(chuàng)建包exercise,在包下創(chuàng)建商品表 Product,類屬性如下:
- 商品標題:title
- 商品庫存:num
- 商品銷量:sales
- 商品描述:comment
- 實現(xiàn) 商品Product類的創(chuàng)建,setter() getter() toString(),
- 通過配置文件bean-product.xml
- 通過set方式注入一組數(shù)據(jù)(商品描述為null值);
- 通過構(gòu)造參數(shù)方式注入一組數(shù)據(jù)(商品描述為null值);
- 創(chuàng)建測試類TestProduct進行測試。
- 練習(xí)答案
① Product類
public class Product {
private String title;
private Integer num;
private Integer sales;
private String comment;
// 無參構(gòu)造函數(shù)、有參構(gòu)造函數(shù) setter() getter() toString()
}
② bean-product.xml
<!-- set方法注入 -->
<bean id="product" class="cn.tedu.spring.exercise.Product">
<property name="title" value="手機"></property>
<property name="num" value="100"></property>
<property name="sales" value="1000"></property>
<property name="comment">
<null></null>
</property>
</bean>
<!-- 構(gòu)造參數(shù)方法注入 -->
<bean id="productCons" class="cn.tedu.spring.exercise.Product">
<constructor-arg name="title" value="電腦"/>
<constructor-arg name="num" value="2"/>
<constructor-arg name="sales" value="3"/>
<constructor-arg name="comment">
<null></null>
</constructor-arg>
</bean>③ ProductTest測試類
@Test
public void testProduct(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-product.xml");
Product product = context.getBean("product", Product.class);
System.out.println("product = " + product);
}
4.5.3 xml實體
- 說明
- < > 小于號、大于號在XML文檔中用來定義標簽的開始,具有特殊含義,在注入屬性值時不能夠隨便使用,
- 可以使用XML實體
< >來代替
- 表示方式
普通字符 | xml實體 |
|---|---|
| < | < |
| > | > |
查看示例 bean-di.xml:
<!-- xml實體 -->
<bean id="filmEntity" class="cn.tedu.spring.DI.Film">
<constructor-arg name="title" value="霸王別姬"></constructor-arg>
<constructor-arg name="actor" value="張國榮"></constructor-arg>
<!--xml實體表示-->
<constructor-arg name="description" value="<真好看啊電影>"></constructor-arg>
</bean>4.5.4 CDATA區(qū)
CDATA區(qū),是xml中一種特有的寫法,在CDATA區(qū)中可以包含特殊符號
表示方式:
? <![CDATA[內(nèi)容]]> ,在內(nèi)容區(qū)域可以存放普通字符和特殊符號
CDATA區(qū)存放特殊符號演示
<!-- xml實體-CDATA區(qū) -->
<bean id="filmCdata" class="cn.tedu.spring.DI.Film">
<constructor-arg name="title" value="霸王別姬"></constructor-arg>
<constructor-arg name="actor" value="張國榮"></constructor-arg>
<!--xml實體表示-->
<constructor-arg name="description">
<!-- CDATA區(qū)存放數(shù)據(jù),可通過 CD + Tab鍵自動補全格式 -->
<value><![CDATA[<真好看啊>]]></value>
</constructor-arg>
</bean>4.6 對象類型屬性注入
需要注入的數(shù)據(jù)類型為對象,而不是一個字面量。
- 環(huán)境準備
- 準備一個一對多案例,比如部門Dept和員工Emp是一對多的關(guān)系。
① 創(chuàng)建包diobj,并創(chuàng)建部門類Dept
public class Dept {
// 部門名稱
private String dName;
// 定義方法,用于測試輸出
public void deptFunc(){
System.out.println("Dept部門名稱:" + dName);
}
public void setdName(String dName) {
this.dName = dName;
}
public String getdName() {
return dName;
}
@Override
public String toString() {
return "Dept{" +
"dName='" + dName + '\'' +
'}';
}
}② 創(chuàng)建員工類Emp,創(chuàng)建setter() getter() 和 toString()方法
public class Emp {
// 員工所屬部門的對象、姓名、工資
private Dept dept;
private String eName;
private Double salary;
// 定義方法測試
public void work(){
System.out.println(eName + "薪資:" + salary);
dept.deptFunc();
}
public void setDept(Dept dept) {
this.dept = dept;
}
public void seteName(String eName) {
this.eName = eName;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Dept getDept() {
return dept;
}
public String geteName() {
return eName;
}
public Double getSalary() {
return salary;
}
@Override
public String toString() {
return "Emp{" +
"dept=" + dept +
", eName='" + eName + '\'' +
", salary=" + salary +
'}';
}
}4.6.1 引用外部bean
說明:
? 可以通過在當前bean標簽中通過 ref屬性引用外部bean的方式實現(xiàn)。
示例:通過使用外部bean方式,在員工中注入部門對象
① 配置文件 bean-diobj.xml
<!--在Emp中注入Dept
方式1:引用外部bean
1.創(chuàng)建兩個類對象:dept 和 emp
2.在emp的bean標簽中,通過property標簽注入dept的bean
-->
<bean id="dept1" class="cn.tedu.spring.diobj.Dept">
<property name="dName" value="開發(fā)部"></property>
</bean>
<bean id="emp1" class="cn.tedu.spring.diobj.Emp">
<!-- 普通屬性注入 -->
<property name="eName" value="張三豐"></property>
<property name="salary" value="50000.0"></property>
<!-- 對象類型注入,使用ref屬性 -->
<property name="dept" ref="dept1"></property>
</bean>② 創(chuàng)建測試類測試 TestDept
public class TestDept {
// 對象類型注入測試用例
@Test
public void testObjDI(){
// 1.加載xml配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean-diobj.xml");
// 2.獲取bean對象
Emp emp1 = context.getBean("emp1", Emp.class);
// 3.測試(調(diào)用員工emp對象的方法)
System.out.println("emp1 = " + emp1);
emp1.work();
}
}4.6.2 內(nèi)部bean
在需要注入對象的bean標簽中內(nèi)嵌 對象類型屬性的 bean標簽即可。
? 內(nèi)嵌bean
① bean-diobj.xml進行屬性注入配置
<!--在Emp中注入Dept
方式2:引用內(nèi)部bean
在emp的bean標簽中,通過內(nèi)嵌部門bean標簽方式實現(xiàn)
-->
<bean id="emp2" class="cn.tedu.spring.diobj.Emp">
<property name="eName" value="張無忌"/>
<property name="salary" value="8000.0"/>
<!--對象注入-->
<property name="dept">
<bean id="dept2" class="cn.tedu.spring.diobj.Dept">
<property name="dName" value="銷售部"/>
</bean>
</property>
</bean>② 使用測試類測試
// 對象類型注入:內(nèi)嵌bean
@Test
public void testObjDi2(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-diobj.xml");
Emp emp2 = context.getBean("emp2", Emp.class);
System.out.println("emp2 = " + emp2);
emp2.work();
}4.6.3 級聯(lián)屬性賦值(了解)
可以在標簽中給需要注入對象的屬性重新賦值!
① 配置文件編寫
<!--方式3:級聯(lián)屬性(需要注入的屬性)賦值-->
<bean id="dept3" class="cn.tedu.spring.diobj.Dept">
<property name="dName" value="市場部"/>
</bean>
<bean id="emp3" class="cn.tedu.spring.diobj.Emp">
<!-- 普通屬性注入 -->
<property name="eName" value="趙敏"/>
<property name="salary" value="5000.0"/>
<!-- 對象類型注入 -->
<property name="dept" ref="dept3"/>
<!-- 級聯(lián)屬性(Dept)賦值 -->
<property name="dept.dName" value="客服部"></property>
</bean>② 測試類測試
// 對象類型注入:級聯(lián)屬性賦值
@Test
public void testObjDi3(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-diobj.xml");
Emp emp3 = context.getBean("emp3", Emp.class);
System.out.println("emp3 = " + emp3);
emp3.work();
}
4.7 數(shù)組類型屬性注入
使用 標簽和子標簽實現(xiàn)。
說明:一個人除了姓名、年齡等屬性外,還會有愛好,一個人的愛好可能有多個,可以把多個愛好存入數(shù)組中。
創(chuàng)建包:cn.tedu.spring.diarray
① 在diarray包中創(chuàng)建類:Person
public class Person {
// 姓名、年齡、愛好
private String name;
private String age;
private String[] hobby;
// 定義測試方法
public void run(){
System.out.println("Persen is running...");
// 打印數(shù)組測試
System.out.println(Arrays.toString(hobby));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", hobby=" + Arrays.toString(hobby) +
'}';
}
}② 新建配置文件:bean-diarray.xml 進行注入
<!-- 創(chuàng)建Person對象并注入屬性 -->
<bean id="person" class="cn.tedu.spring.diarray.Person">
<!-- 普通屬性注入 -->
<property name="name" value="孫悟空"/>
<property name="age" value="36"/>
<!-- 數(shù)組屬性注入,使用<array>標簽 -->
<property name="hobby">
<array>
<value>抽煙</value>
<value>喝酒</value>
<value>燙頭</value>
</array>
</property>
</bean>③ 編寫測試類TestPerson測試
public class TestPerson {
// 數(shù)組注入測試用例
@Test
public void testArray(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-diarray.xml");
Person person = context.getBean("person", Person.class);
System.out.println("person = " + person);
person.run();
}
}4.8 集合類型屬性注入
4.8.1 List集合屬性注入
場景1:使用 標簽下的 子標簽和 子標簽實現(xiàn)。
場景2:使用 標簽下的 子標簽和子標簽實現(xiàn)。ref標識引用其他的bean
環(huán)境說明:創(chuàng)建老師類Student和學(xué)生類Student,一個老師可以有多個學(xué)生,在老師類中存入所教學(xué)生的對象,將其存入List集合中。
環(huán)境準備
① 創(chuàng)建包 dimap
② Teacher類
public class Teacher {
// 老師姓名
private String tName;
// 老師所教學(xué)生的對象,放到List集合中
private List<Student> studentList;
public String gettName() {
return tName;
}
public void settName(String tName) {
this.tName = tName;
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
@Override
public String toString() {
return "Teacher{" +
"tName='" + tName + '\'' +
", studentList=" + studentList +
'}';
}
}③ Student類
public class Student {
// 學(xué)生姓名、年齡
private String sName;
private String age;
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"sName='" + sName + '\'' +
", course='" + course + '\'' +
'}';
}
}④ 創(chuàng)建配置文件:bean-dilistmap.xml 進行注入
<!-- 創(chuàng)建2個Student對象,用于Teacher對象的注入 -->
<bean id="stu1" class="cn.tedu.spring.dimap.Student">
<property name="sName" value="梁山伯"/>
<property name="age" value="43"/>
</bean>
<bean id="stu2" class="cn.tedu.spring.dimap.Student">
<property name="sName" value="祝英臺"/>
<property name="age" value="33"/>
</bean>
<!-- 創(chuàng)建Teacher類的bean對象,并注入屬性 -->
<bean id="teacher" class="cn.tedu.spring.dimap.Teacher">
<!-- 普通屬性注入 -->
<property name="tName" value="沙師弟"/>
<!-- List集合屬性注入 -->
<property name="studentList">
<list>
<ref bean="stu1"/>
<ref bean="stu2"/>
</list>
</property>
</bean>⑤ 測試類TestTeacher測試
public class TestTeacher {
@Test
public void testListMap(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-dilistmap.xml");
Teacher teacher = context.getBean("teacher", Teacher.class);
System.out.println("teacher = " + teacher);
List<Student> list = teacher.getStudentList();
for (Student student: list) {
System.out.println(student);
}
}
}4.8.2 Map集合屬性注入
使用標簽下的子標簽、子標簽、子標簽 子標簽 子標簽實現(xiàn)
<bean id="xxx" class="xxx">
<property name="xxx">
<map>
<!-- 第1條數(shù)據(jù)-字面量值演示 -->
<entry>
<key><value>xxx</value></key>
<value>xxx</value>
</entry>
<!-- 第2條數(shù)據(jù)-對象演示 -->
<entry>
<key><value>xxx</value></key>
<ref bean="xxx"></ref>
</entry>
</map>
</property>
</bean>說明:使用上述的老師類和學(xué)生類,一個學(xué)生也可以有多個老師,在學(xué)生類Student中添加老師的屬性,放到Map集合中。
① 調(diào)整Student類
// 1.學(xué)生的老師:可以有多個,放到Map集合中 private Map<String,String> teacherMap; // 2.生成setter() getter()方法,重新生成toString()方法
② 創(chuàng)建配置文件:bean-dimap.xml
<!--Map集合屬性注入-->
<bean id="stuMap" class="cn.tedu.spring.dilistmap.Student">
<property name="sName" value="步驚云"/>
<property name="age" value="36"/>
<property name="teacherMap">
<map>
<entry>
<key>
<value>1111</value>
</key>
<value>雄霸</value>
</entry>
<entry>
<key>
<value>2222</value>
</key>
<value>斷浪</value>
</entry>
<entry>
<key>
<value>3333</value>
</key>
<value>大空翼</value>
</entry>
</map>
</property>
</bean>③ 創(chuàng)建測試類進行測試 TestMap
@Test
public void testMap(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-dimap.xml");
Student student = context.getBean("stuMap", Student.class);
System.out.println("student = " + student);
}
4.8.3 引用集合類型bean注入
- 說明
- 通過使用 標簽實現(xiàn)
- 使用步驟
- 在xml配置文件中引入util約束
<beans
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"
>
</beans>使用util標簽進入注入
<!-- Map集合util標簽 --> <util:map id="xxx"></util:map> <!-- List集合util標簽 --> <util:list id="xxx"></util:list>
環(huán)境準備及操作步驟
添加課程類,一個學(xué)生可以上多門課程
① 在Student類中添加List集合屬性
// 1.一個學(xué)生可以上多門課程,把課程名稱放到List集合中
private List<String> courseList;
// 2.生成get和set方法
// 3.重新生成toString()方法② 創(chuàng)建spring配置文件:bean-diref.xml,引入util約束
<!-- 添加3行帶有util的配置 -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>③ 配置xml文件完成注入
<!--引用集合類型bean注入-->
<bean id="stuUtil" class="cn.tedu.spring.dilistmap.Student">
<property name="sName" value="孔慈"/>
<property name="age" value="36"/>
<property name="teacherMap" ref="teacherMap"></property>
<property name="courseList" ref="courseList"></property>
</bean>
<util:map id="teacherMap">
<entry>
<key>
<value>10000</value>
</key>
<value>小澤老師</value>
</entry>
<entry>
<key>
<value>10001</value>
</key>
<value>王老師</value>
</entry>
</util:map>
<util:list id="courseList">
<value>Spring</value>
<value>SpringMVC</value>
<value>MyBatis</value>
</util:list>④ 創(chuàng)建測試方法進行測試
// 引用集合類型bean注入(util)
@Test
public void testRefBean(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-diref.xml");
Student student = context.getBean("stuUtil", Student.class);
System.out.println("student = " + student);
}
4.9 p命名空間
這也是一種注入方式,可以在xml中定義命名空間或者叫名稱空間,可以簡化xml代碼。
在bean-diref.html中操作
① 在xml配置文件中定義命名空間
xmlns:p="http://www.springframework.org/schema/p"
② 在xml文件進行命名空間屬性注入
<!-- p命名空間注入: 注入學(xué)生屬性 --> <bean id="studentp" class="cn.tedu.spring.iocxml.dimap.Student" p:sid="100" p:sname="鐵錘妹妹" p:courseList-ref="courseList" p:teacherMap-ref="teacherMap">
③ 測試
// p命名空間注入測試用例
@Test
public void testRefP(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-diref.xml");
Student studentp = context.getBean("studentp", Student.class);
System.out.println("studentp = " + studentp);
}
4.10 引入外部屬性文件
- 說明
- ? 當前所有的配置和數(shù)據(jù)都在xml文件中,一個文件中有很多bean,修改和維護起來很不方便,生產(chǎn)環(huán)境中會把特定的固定值放到外部文件中,然后引入外部文件進行注入,比如數(shù)據(jù)庫連接信息。
- 示例
- 將外部文件中的數(shù)據(jù)引入xml配置文件進行注入
① pom.xml中引入數(shù)據(jù)庫相關(guān)依賴,并刷新maven
<!-- MySQL驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- 數(shù)據(jù)源,連接池依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>② resources目錄下創(chuàng)建外部屬性文件,一般為properties格式,定義數(shù)據(jù)庫信息,比如:jdbc.properties
jdbc.user=root jdbc.password=root jdbc.url=jdbc://mysql://localhost:3306/spring jdbc.driver=com.mysql.cj.jdbc.Driver
③ 創(chuàng)建spring配置文件bean-jdbc.xml,引入context的命名空間
使用context可以為XML外部實體注入定義,使得解析器在解析XML文檔時可以正確地識別外部實體
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 引入外部屬性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- 完成數(shù)據(jù)庫信息注入 -->
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
</bean>
</beans>④ 創(chuàng)建包jdbc,包中創(chuàng)建測試類 TestJdbc
public class TestJdbc {
// 外部文件屬性引入測試用例
@Test
public void demo02(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-jdbc.xml");
DruidDataSource druidDataSource = context.getBean("druidDataSource", DruidDataSource.class);
System.out.println(druidDataSource.getUrl());
}
}4.11 bean的作用域
- 說明
- ? bean的作用域,是指在交給spring創(chuàng)建bean對象時,可以指定是單實例還是多實例,通過bean標簽中的scope屬性來指定,默認是單實例。
- 單實例和多實例
- 單實例
- 單實例(Singleton)是指某個類只能創(chuàng)建唯一的一個實例對象,并且該類提供一個全局的訪問點(靜態(tài)方法)來讓外界獲取這個實例,常常用在那些只需要一個實例來處理所有任務(wù)的場景下,例如配置類或數(shù)據(jù)庫連接池等。
- 多實例
- 多實例(Multiple Instance)則是指可以在同一個類的定義下,創(chuàng)建多個實例對象。每個對象都是相互獨立的,有自己的狀態(tài)和行為;常常用于需要同時處理多個任務(wù)的場景。
在Spring中可以通過配置bean標簽的scope屬性來之地那個bean的作用域范圍,具體如下
| 取值 | 含義 | 創(chuàng)建對象時機 |
|---|---|---|
| singleton(默認) | 在IoC容器中,這個bean的對象為單實例 | IoC容器初始化時 |
| prototype | 這個bean在IoC容器中有多個實例 | 獲取bean時 |
案例演示
① 創(chuàng)建包scope,并在包下創(chuàng)建類Sku
public class Sku {
}② 創(chuàng)建spring的配置文件:bean-scope.xml
<!-- singleton:單實例 --> <!-- 之后改為prototype多實例測試 --> <bean id="sku" class="cn.tedu.spring.scope.Sku" scope="singleton"></bean>
③ 創(chuàng)建測試類TestOrders
@Test
public void testOrders(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-scope.xml");
Orders orders = context.getBean("orders", Orders.class);
System.out.println("orders = " + orders);
Orders orders1 = context.getBean("orders", Orders.class);
System.out.println("orders1 = " + orders1);
}
// 單實例,sku1和sku2地址相同
// 多實例,sku1和sku2地址不同
4.12 bean的生命周期
是指一個bean對象從創(chuàng)建到銷毀的整個過程。
4.12.1 bean的完整生命周期
- 實例化階段(bean對象創(chuàng)建)
- 在這個階段中,容器會創(chuàng)建一個Bean的實例,并為其分配空間。這個過程可以通過構(gòu)造方法完成。
- 屬性賦值階段
- 在實例化完Bean之后,容器會把Bean中的屬性值注入到Bean中,這個過程可以通過set方法完成。
- 初始化階段(bean對象初始化)
- 在屬性注入完成后,容器會對Bean進行一些初始化操作;
- 初始化之前:bean的后置處理器可以接收到bean,此處可以對bean做相關(guān)操作。
- 初始化之后:bean的后置處理器可以接收到bean,此處可以對bean做相關(guān)操作。
- 使用階段
- 初始化完成后,Bean就可以被容器使用了
- 銷毀階段
- 容器在關(guān)閉時會對所有的Bean進行銷毀操作,釋放資源。
4.12.2 生命周期驗證
① 創(chuàng)建包life,創(chuàng)建類User
package cn.tedu.spring.life;
import org.springframework.beans.BeansException;
public class User {
private String username;
// 1.無參數(shù)構(gòu)造
public User(){
System.out.println("1-bean對象創(chuàng)建,調(diào)用無參數(shù)構(gòu)造。");
}
// 3.初始化階段
public void initMethod(){
System.out.println("3-bean對象初始化,調(diào)用指定的初始化方法");
}
// 5.銷毀階段
public void destoryMethod(){
System.out.println("5-bean對象銷毀,調(diào)用指定的銷毀方法");
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
// 2.給bean對象屬性賦值
System.out.println("2-通過set方法給bean對象賦值。");
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
'}';
}
}② 創(chuàng)建spring配置文件 bean-life.xml
<bean id="user" class="cn.tedu.spring.iocxml.life.User" scope="singleton"
init-method="initMethod" destroy-method="destroyMethod">
<property name="username" value="聶風(fēng)"></property>
</bean>③ 創(chuàng)建測試類TestUser測試
@Test
public void testUser(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean-life.xml");
User user = context.getBean("user", User.class);
// 4.bean對象初始化完成,可以使用
System.out.println("4-bean對象初始化完成,開發(fā)者可以使用了。");
// 銷毀bean
context.close();
}
④ 后置處理器處理演示,新建類MyBeanPost
public class MyBeanPost implements BeanPostProcessor {
// BeanPostProcessor接口
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("3之前:bean后置處理器,在初始化之前執(zhí)行。" + beanName + ":" + bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("3之后:bean后置處理器,在初始化之后執(zhí)行。" + beanName + ":" + bean);
return bean;
}
}⑤ 在spring的配置文件bean-life.xml中進行后置處理器配置
<!-- bean的后置處理器需要放到IoC容器中才能生效 --> <bean id="myBeanPost" class="cn.tedu.spring.life.MyBeanPost"></bean>
⑥ 運行測試類測試
4.12.3 bean生命周期擴展
- bean的初始化和銷毀應(yīng)用場景
- 初始化
- 創(chuàng)建連接池
- 加載資源文件
- 進行數(shù)據(jù)校驗
- 初始化
- 銷毀
- 關(guān)閉連接池
- 保存數(shù)據(jù)
- 釋放占用的資源
- 后置處理器
- 實現(xiàn)自定義的Bean對象處理邏輯,比如在Bean實例化之前或者之后對Bean對象進行自定義的修改,可以方便地實現(xiàn)自定義邏輯和修改Bean對象的行為。
4.13 基于xml自動裝配
自動裝配說明:
根據(jù)指定的策略,在IoC容器中匹配某一個bean,自動為指定的bean中的所依賴的類類型或者接口類型屬性賦值。
環(huán)境準備
① 創(chuàng)建包auto,創(chuàng)建部門和員工的兩個java類
② 部門類 Dept
public class Dept {
private String dName;
@Override
public String toString() {
return "Dept{" +
"dName='" + dName + '\'' +
'}';
}
public String getdName() {
return dName;
}
public void setdName(String dName) {
this.dName = dName;
}
}③ 員工類 Emp
public class Emp {
private String eName;
private Dept dept;
@Override
public String toString() {
return "Emp{" +
"eName='" + eName + '\'' +
", dept=" + dept +
'}';
}
public String geteName() {
return eName;
}
public void seteName(String eName) {
this.eName = eName;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}④ 創(chuàng)建spring配置文件bean-auto.xml
<!--通過byType和byName自動裝配-->
<bean id="dept" class="cn.tedu.spring.iocxml.auto.Dept">
<property name="dName" value="技術(shù)部"></property>
</bean>
<!--autowire="byType" 或者 autowire="byName"-->
<bean id="emp" class="cn.tedu.spring.iocxml.auto.Emp" autowire="byType">
<property name="eName" value="步驚云"></property>
</bean>⑤ 創(chuàng)建測試類測試TestAuto
@Test
public void testAuto(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean-auto.xml");
Emp emp = context.getBean("emp", Emp.class);
System.out.println("emp = " + emp);
}使用bean標簽的autowire屬性設(shè)置自動裝配效果;
自動裝配方式:byType
? byType: 根據(jù)類型匹配IoC容器中的某個兼容類型的bean,為屬性自動賦值;
? 1. 如果在IoC中,沒有任何一個兼容類型的bean能夠為屬性賦值,則改屬性不裝配,默認值為null;
? 2. 如果在IoC中,有多個兼容類型的bean能夠為屬性賦值,則拋出異常 NoUniqueBeanDefinitionException
自動裝配方式:byName
? byName:將自動裝配的屬性名,作為bean的id在IoC容器中匹配相對應(yīng)的bean進行賦值
5 基于注解管理bean
? 從Java5開始,Java增加了對注解(Annotation)的支持,它是代碼中的一種特殊標記,可以在編譯、類加載和運行時被讀取,執(zhí)行相應(yīng)的處理。開發(fā)人員可以通過注解在不改變原有代碼和邏輯的情況下,在源代碼中嵌入補充信息。
? Spring從2.5版本開始提供了對注解技術(shù)的全面支持,我們可以使用注解來實現(xiàn)自動裝配,簡化Spring的xml配置。
Spring通過注解實現(xiàn)自動裝配:
- 引入依賴
- 開啟組件掃描
- 使用注解定義Bean
- 依賴注入
5.1 創(chuàng)建子工程
子工程:spring-ioc-annotation
在pom.xml中添加springframework的依賴,刷新maven
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
</dependencies>5.2 開啟組件掃描
? Spring默認不使用注解裝配Bean,因此需要在Spring的xml配置中,通過context:component-scan元素開啟Spring Beans的自動掃描功能。開啟此功能后,Spring會自動從掃描指定的包(base-package屬性設(shè)置)及其子包下的所有類,如果類上使用了@Component注解,就將該類裝配到容器中。
① 工程下創(chuàng)建包:cn.tedu.spring.bean
② resources目錄下創(chuàng)建spring配置文件 bean.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 2.開啟組件掃描,讓spring可以通過注解方式實現(xiàn)bean管理,包括創(chuàng)建對象、屬性注入 -->
<!-- base-package:掃描哪個包中的注解,在cn.tedu的包或者子包中建了類,在
類上、屬性上、方法上加了spring的@Component注解,這里就能掃描到-->
<context:component-scan base-package="cn.tedu.spring"></context:component-scan>
</beans>5.3 使用注解定義Bean
Spring提供了以下多個注解,這些注解可以直接標注在java類上,將它們定義成Spring Bean。
| 注解 | 說明 |
|---|---|
| @Component | 該注解用于描述Spring中的Bean,它是一個泛化的概念,僅僅標識容器中的一個組件(Bean),并且可以作用在任何層次,例如Service層、Dao層等,使用時只需將該注解標注在相應(yīng)的類上即可。 |
| @Respository | 該注解用于數(shù)據(jù)訪問層(Dao層)的類標識為Spring中的Bean,功能與@Component相同。 |
| @Service | 該注解通常作用在業(yè)務(wù)層(Service層),用于將業(yè)務(wù)層的類標識為Spring中的Bean,其功能與@Component相同。 |
| @Controller | 該注解通常作用在控制層(如SpringMVC的Controller),用于將控制層的類標識為Spring中的Bean,其功能與@Component相同。 |
③ 創(chuàng)建User類,并添加注解
// value可以不寫,默認為類名首字母小寫
//@Component(value = "user") // <bean id="user" class="xxx">
//@Repository
//@Service
@Controller
public class User {
}
④ 創(chuàng)建測試類測試TestUser
public class TestUser {
@Test
public void testUser(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
User user = context.getBean("user", User.class);
System.out.println("user = " + user);
}
}
5.4 @Autowired注入
單獨使用@Autowired注解,默認根據(jù)類型裝配(byType)
@Autowired注解有一個required屬性,默認值是true,表示在注入的時候要求被注入的Bean必須存在,如果不存在則報錯。如果required屬性設(shè)置為false,表示注入的Bean存在或者不存在都沒關(guān)系,存在就注入,不存在也不報錯。
5.4.1 屬性注入
① cn.tedu.spring下創(chuàng)建包autowired,并在autowired下創(chuàng)建兩個包:controller包 和 service包
② 控制器層controller.UserController
public class UserController {
private UserService userService;
public void addController(){
System.out.println("controller is running...");
userService.addService();
}
}③ 服務(wù)層service.UserService接口
public interface UserService {
public void addService();
}
④ 服務(wù)層service.UserServiceImpl接口的實現(xiàn)類
public class UserServiceImpl implements UserService {
@Override
public void addService() {
System.out.println("service is running...");
}
}⑤ 在UserController和UserSerivceImpl中添加@Controller注解和@Service注解
⑥ 在UserController中注入UserServiceImpl
@Controller
public class UserController {
// 注入service
// 第一種方式:屬性注入
@Autowired // 根據(jù)類型找到對象,完成注入
private UserService userService;
}
⑦ 測試類測試autowired.TestUserController
public class TestUserController {
@Test
public void testUserController(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
UserController controller = context.getBean(UserController.class);
controller.addController();
}
}5.4.2 set注入
① 修改UserController類
// 方式二:通過set方法注入
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}② 測試
5.4.3 構(gòu)造方法注入
① 修改UserController類
// 第三種方式:構(gòu)造方法注入
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}② 測試
5.4.4 形參上注入
① 修改UserController類
// 第四種方式:形參注入
private UserService userService;
public UserController(@Autowired UserService userService) {
this.userService = userService;
}② 測試
5.4.5 只有一個構(gòu)造函數(shù),無注解
① 修改UserController類
// 第五種方式:只有一個有參數(shù)構(gòu)造函數(shù),無注解
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}② 測試
5.4.6 @Autowire注解和@Qualifier注解聯(lián)合
① 再創(chuàng)建一個UserService接口的實現(xiàn)類service.UserServiceImpl2
@Service
public class UserServiceImpl2 implements UserService{
@Override
public void addService() {
System.out.println("service2 is running...");
}
}② 測試發(fā)現(xiàn)報錯
? 因為UserService有兩個實現(xiàn)類,而@Autowired注解根據(jù)byType定位,所以找到了兩個實現(xiàn)類
③ 解決:修改UserController (使用兩個注解)
// 1.第六種方式:根據(jù)類型和名稱一起注入 @Autowired @Qualifier(value = "userServiceImpl2") // 類名首字母小寫 private UserService userService; // 2.將構(gòu)造函數(shù)注釋
5.5 @Resource注入
@Resource注解也可以完成屬性注入。它和@Autowired注解的區(qū)別如下
- @Resource注解是JDK擴展包中的,也就是說屬于JDK的一部分。所以該解釋是標準注解,更加具有通用性,而@Autowired注解是Spring框架自己的。
- @Resource注解默認根據(jù)名稱裝配byName,未指定name時,使用屬性名作為name,通過name找不到的話會自動啟動通過類型byType裝配。而@Autowired注解默認根據(jù)類型裝配byType,如果想根據(jù)名稱匹配,需要配合@Qualifier注解一起使用。
- @Resource注解用在屬性上、setter方法上
- @Autowired注解用在屬性上、setter方法上、構(gòu)造方法上、構(gòu)造方法參數(shù)上。
案例演示
① 工程下創(chuàng)建包 resource,和之前一樣,創(chuàng)建controller和service兩個包,并創(chuàng)建UserController類和UserService接口以及該接口的實現(xiàn)類UserServiceImpl
② 修改UserController
@Controller("myUserController")
public class UserController {
// 根據(jù)名稱進行注入
@Resource(name="myUserService")
private UserService userService;
public void add(){
System.out.println("controller...");
userService.add();
}
}③ 修改ServiceControllerImpl1
@Service("myUserService")
public class UserServiceImpl implements UserService {
⑤ 測試
- 指定@Resource中的name,則根據(jù)名稱裝配
- 未指定name時,則根據(jù)屬性名裝配
- 未指定name,屬性名也不一致,則根據(jù)類型裝配
5.6 Spring全注解開發(fā)
全注解開發(fā)就是不再使用spring配置文件了,寫一個配置類來代替配置文件。
① 工程下創(chuàng)建包:config,創(chuàng)建類SpringConfig
// 配置類
@Configuration
// 開啟組件掃描
@ComponentScan("cn.tedu.spring")
public class SpringConfig {
}
② 在resource下創(chuàng)建測試類進行測試
public class TestUserControllerAnno {
public static void main(String[] args) {
// 加載配置類
ApplicationContext context =
new AnnotationConfigApplicationContext(SpringConfig.class);
UserController controller = context.getBean(UserController.class);
controller.add();
}
}到此這篇關(guān)于spring全面詳解-最全最詳細的spring基本認識和入門使用的文章就介紹到這了,更多相關(guān)spring內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis實現(xiàn)聯(lián)表查詢并且分頁功能
這篇文章主要介紹了Mybatis實現(xiàn)聯(lián)表查詢并且分頁功能,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
Java for-each循環(huán)(遍歷循環(huán))詳解
本文詳解Java for-each循環(huán),涵蓋其簡化遍歷、類型安全、不可變性、空指針防護等特性,適用場景及限制,錯誤案例與修正,性能對比,高級技巧(如Java14 Records),并提供最佳實踐指南2025-07-07
springboot之SpringApplication生命周期和事件機制解讀
這篇文章主要介紹了springboot之SpringApplication生命周期和事件機制,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
Java實現(xiàn)多級表頭和復(fù)雜表頭的導(dǎo)出功能
這篇文章主要為大家詳細介紹了Java實現(xiàn)多級表頭和復(fù)雜表頭的導(dǎo)出功能的相關(guān)知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03
SpringBoot框架中Mybatis-plus的簡單使用操作匯總
這篇文章主要介紹了SpringBoot框架中Mybatis-plus的簡單使用,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02

