一、搭建模組spring6-ioc-xml
①引入配置檔案
引入spring6-ioc-xml模組配置檔案:beans.xml、log4j2.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.mcode.bean.User"/>
</beans>
②新增依賴
<dependencies>
<!--spring context依賴-->
<!--當你引入Spring Context依賴之後,表示將Spring的基礎依賴引入了-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.13</version>
</dependency>
<!--junit5測試-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.3</version>
</dependency>
<!--log4j2的依賴-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.20.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.20.0</version>
</dependency>
</dependencies>
③引入java類
引入spring6-ioc-xml模組java及test目錄下實體類
package com.mcode.bean;
/**
* ClassName: User
* Package: com.mcode.bean
* Description:
*
* @Author: robin
* @Create: 2023/11/7 - 10:33 PM
* @Version: v1.0
*/
public class User {
public User() {
System.out.println("無引數構造方法執行");
}
public void test(){
System.out.println("test...");
}
}
package com.mcode;
import com.mcode.bean.Student;
import com.mcode.bean.User;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* ClassName: UserTest
* Package: com.mcode
* Description:
*
* @Author: robin
* @Create: 2023/11/7 - 10:34 PM
* @Version: v1.0
*/
public class UserTest {
private Logger logger = LoggerFactory.getLogger(UserTest.class);
@Test
public void testUser(){
}
}
二、獲取bean的三種方式
①方式一:根據id獲取
由於 id 屬性指定了 bean 的唯一標識,所以根據 bean 標籤的 id 屬性可以精確獲取到一個元件物件。
@Test
public void testUser(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) applicationContext.getBean("user");
user.test();
}
②方式二:根據型別獲取
@Test
public void testUser1(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) applicationContext.getBean(User.class);
user.test();
}
③方式三:根據id和型別
@Test
public void testUser2(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) applicationContext.getBean("user",User.class);
user.test();
}
④注意的地方
當根據型別獲取bean時,要求IOC容器中指定型別的bean有且只能有一個
當IOC容器中一共配置了兩個:
<bean id="user" class="com.mcode.bean.User"/>
<bean id="user2" class="com.mcode.bean.User"/>
根據型別獲取時會丟擲異常:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.mcode.bean.User' available: expected single matching bean but found 2: user,user2
三、基於setter注入
①建立學生類Student
package com.mcode.bean;
/**
* ClassName: Student
* Package: com.mcode.bean
* Description:
*
* @Author: robin
* @Create: 2023/11/7 - 10:46 PM
* @Version: v1.0
*/
public class Student {
private Integer id;
private String name;
private Integer age;
private String sex;
public Student() {
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
②配置bean時為屬性賦值
spring-di.xml
<bean id="studentOne" class="com.mcode.bean.Student">
<!-- property標籤:透過元件類的setXxx()方法給元件物件設定屬性 -->
<!-- name屬性:指定屬性名(這個屬性名是getXxx()、setXxx()方法定義的,和成員變數無關) -->
<!-- value屬性:指定屬性值 -->
<property name="id" value="1"></property>
<property name="name" value="robin"></property>
<property name="age" value="18"></property>
<property name="sex" value="男"></property>
</bean>
③測試
@Test
public void testDIBySet(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-di.xml");
Student student = applicationContext.getBean("studentOne", Student.class);
System.out.println(student);
}
四、基於構造器注入
①在Student類中新增有參構造
public Student(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
②配置bean
spring-di.xml
<bean id="studentTwo" class="com.mcode.bean.Student">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="robin"></constructor-arg>
<constructor-arg value="20"></constructor-arg>
<constructor-arg value="男"></constructor-arg>
</bean>
注意:
constructor-arg標籤還有兩個屬性可以進一步描述構造器引數:
- index屬性:指定引數所在位置的索引(從0開始)
- name屬性:指定引數名
③測試
@Test
public void testDIByConstructor(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-di.xml");
Student student = applicationContext.getBean("studentTwo", Student.class);
System.out.println(student);
}
五、特殊值處理
①字面量賦值
什麼是字面量?
int a = 10;
宣告一個變數a,初始化為10,此時a就不代表字母a了,而是作為一個變數的名字。當我們引用a的時候,我們實際上拿到的值是10。
而如果a是帶引號的:'a',那麼它現在不是一個變數,它就是代表a這個字母本身,這就是字面量。所以字面量沒有引申含義,就是我們看到的這個資料本身。
<!-- 使用value屬性給bean的屬性賦值時,Spring會把value屬性的值看做字面量 -->
<property name="name" value="張三"/>
②null值
<property name="name">
<null />
</property>
注意:
<property name="name" value="null"></property>
以上寫法,為name所賦的值是字串null
③xml實體
<!-- 小於號在XML文件中用來定義標籤的開始,不能隨便使用 -->
<!-- 解決方案一:使用XML實體來代替 -->
<property name="expression" value="a < b"/>
④CDATA節
<property name="expression">
<!-- 解決方案二:使用CDATA節 -->
<!-- CDATA中的C代表Character,是文字、字元的含義,CDATA就表示純文字資料 -->
<!-- XML解析器看到CDATA節就知道這裡是純文字,就不會當作XML標籤或屬性來解析 -->
<!-- 所以CDATA節中寫什麼符號都隨意 -->
<value><![CDATA[a < b]]></value>
</property>
六、為物件型別屬性賦值
①建立班級類Clazz
package com.mcode.bean;
/**
* ClassName: Clazz
* Package: com.mcode.bean
* Description:
*
* @Author: robin
* @Create: 2023/11/7 - 10:53 PM
* @Version: v1.0
*/
public class Clazz {
private Integer clazzId;
private String clazzName;
public Clazz() {
}
public Clazz(Integer clazzId, String clazzName) {
this.clazzId = clazzId;
this.clazzName = clazzName;
}
@Override
public String toString() {
return "Clazz{" +
"clazzId=" + clazzId +
", clazzName='" + clazzName + '\'' +
'}';
}
public Integer getClazzId() {
return clazzId;
}
public void setClazzId(Integer clazzId) {
this.clazzId = clazzId;
}
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
}
②修改Student類
在Student類中新增以下程式碼:
private Clazz clazz;
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
方式一:引用外部bean
配置Clazz型別的bean:
<bean id="clazzOne" class="com.mcode.bean.Clazz">
<property name="clazzId" value="1111"></property>
<property name="clazzName" value="財源滾滾班"></property>
</bean>
為Student中的clazz屬性賦值:
<bean id="studentFour" class="com.mcode.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref屬性:引用IOC容器中某個bean的id,將所對應的bean為屬性賦值 -->
<property name="clazz" ref="clazzOne"></property>
</bean>
方式二:內部bean
<bean id="studentFour" class="com.mcode.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<property name="clazz">
<!-- 在一個bean中再宣告一個bean就是內部bean -->
<!-- 內部bean只能用於給屬性賦值,不能在外部透過IOC容器獲取,因此可以省略id屬性 -->
<bean id="clazzInner" class="com.mcode.bean.Clazz">
<property name="clazzId" value="2222"></property>
<property name="clazzName" value="遠大前程班"></property>
</bean>
</property>
</bean>
方式三:級聯屬性賦值
<bean id="studentFour" class="com.mcode.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="趙六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<property name="clazz" ref="clazzOne"></property>
<property name="clazz.clazzId" value="3333"></property>
<property name="clazz.clazzName" value="最強王者班"></property>
</bean>
七、引入外部屬性檔案
①加入依賴
<!-- MySQL驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 資料來源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
②建立外部屬性檔案
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver
③引入屬性檔案
引入context 名稱空間
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
<!-- 引入外部屬性檔案 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
注意:在使用 context:property-placeholder 元素載入外包配置檔案功能前,首先需要在 XML 配置的一級標籤
中新增 context 相關的約束。
④配置bean
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
⑤測試
@Test
public void testDataSource() throws SQLException {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-datasource.xml");
DataSource dataSource = ac.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
八、基於XML自動裝配
自動裝配:
根據指定的策略,在IOC容器中匹配某一個bean,自動為指定的bean中所依賴的類型別或介面型別屬性賦值
①場景模擬
建立類UserController
package com.mcode.autowire.controller;
import com.mcode.autowire.service.UserService;
/**
* ClassName: UserController
* Package: com.mcode.autowire.controller
* Description:
*
* @Author: robin
* @Create: 2023/11/7 - 11:29 PM
* @Version: v1.0
*/
public class UserController {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void getUser(){
userService.getUser();
}
}
建立介面UserService
package com.mcode.autowire.service;
/**
* ClassName: UserService
* Package: com.mcode.autowite.service
* Description:
*
* @Author: robin
* @Create: 2023/11/7 - 11:30 PM
* @Version: v1.0
*/
public interface UserService {
void getUser();
}
建立類UserServiceImpl實現介面UserService
package com.mcode.autowire.service.impl;
import com.mcode.autowire.service.UserService;
/**
* ClassName: UserServiceImpl
* Package: com.mcode.autowire.service.impl
* Description:
*
* @Author: robin
* @Create: 2023/11/7 - 11:31 PM
* @Version: v1.0
*/
public class UserServiceImpl implements UserService {
@Override
public void getUser() {
System.out.println("獲取user...");
}
}
②配置bean
使用bean標籤的autowire屬性設定自動裝配效果
自動裝配方式:byType
byType:根據型別匹配IOC容器中的某個相容型別的bean,為屬性自動賦值
若在IOC中,沒有任何一個相容型別的bean能夠為屬性賦值,則該屬性不裝配,即值為預設值null
若在IOC中,有多個相容型別的bean能夠為屬性賦值,則丟擲異常NoUniqueBeanDefinitionException
<?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">
<bean id="userService" class="com.mcode.autowire.service.impl.UserServiceImpl"/>
<bean id="userController" class="com.mcode.autowire.controller.UserController" autowire="byType"/>
</beans>
自動裝配方式:byName
byName:將自動裝配的屬性的屬性名,作為bean的id在IOC容器中匹配相對應的bean進行賦值
<?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">
<bean id="userService" class="com.mcode.autowire.service.impl.UserServiceImpl"/>
<bean id="userController" class="com.mcode.autowire.controller.UserController" autowire="byName"/>
</beans>
③測試
@Test
public void testAutoWireByXML(){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-autowire.xml");
UserController userController = ac.getBean(UserController.class);
userController.getUser();
}