目录
- 一、搭建模块spring6-ioc-xml
- 二、获取bean的三种方式
- 三、基于setter注入
- 四、基于构造器注入
- 五、特殊值处理
- 六、为对象类型属性赋值
- 七、引入外部属性文件
- 八、基于XML自动装配
一、搭建模块spring6-ioc-xml
①引入配置文件
引入spring6-ioc-xml模块配置文件:beans.xml、log4j2.xml
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>
②添加依赖
xml
<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目录下实体类
java
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...");
}
}
java
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 属性可以精确获取到一个组件对象。
java
@Test
public void testUser(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) applicationContext.getBean("user");
user.test();
}
②方式二:根据类型获取
java
@Test
public void testUser1(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) applicationContext.getBean(User.class);
user.test();
}
③方式三:根据id和类型
java
@Test
public void testUser2(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) applicationContext.getBean("user",User.class);
user.test();
}
④注意的地方
当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个
当IOC容器中一共配置了两个:
xml
<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
java
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
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>
③测试
java
@Test
public void testDIBySet(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-di.xml");
Student student = applicationContext.getBean("studentOne", Student.class);
System.out.println(student);
}
四、基于构造器注入
①在Student类中添加有参构造
java
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
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属性:指定参数名
③测试
java
@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这个字母本身,这就是字面量。所以字面量没有引申含义,就是我们看到的这个数据本身。
xml
<!-- 使用value属性给bean的属性赋值时,Spring会把value属性的值看做字面量 -->
<property name="name" value="张三"/>
②null值
xml
<property name="name">
<null />
</property>
注意:
xml<property name="name" value="null"></property>
以上写法,为name所赋的值是字符串null
③xml实体
xml
<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="expression" value="a < b"/>
④CDATA节
xml
<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>
六、为对象类型属性赋值
①创建班级类Clazz
java
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类中添加以下代码:
java
private Clazz clazz;
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
方式一:引用外部bean
配置Clazz类型的bean:
xml
<bean id="clazzOne" class="com.mcode.bean.Clazz">
<property name="clazzId" value="1111"></property>
<property name="clazzName" value="财源滚滚班"></property>
</bean>
为Student中的clazz属性赋值:
xml
<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
xml
<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>
方式三:级联属性赋值
xml
<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>
七、引入外部属性文件
①加入依赖
xml
<!-- 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>
②创建外部属性文件
properties
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver
③引入属性文件
引入context 名称空间
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/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>
xml
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
注意:在使用 context:property-placeholder 元素加载外包配置文件功能前,首先需要在 XML 配置的一级标签 中添加 context 相关的约束。
④配置bean
xml
<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>
⑤测试
java
@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
java
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
java
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
java
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
<?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
<?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>
③测试
java
@Test
public void testAutoWireByXML(){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-autowire.xml");
UserController userController = ac.getBean(UserController.class);
userController.getUser();
}