Spring系列:基于XML的方式构建IOC
一、搭建模块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();
}
Spring系列:基于XML的方式构建IOC的更多相关文章
- Spring 框架的概述以及Spring中基于XML的IOC配置
Spring 框架的概述以及Spring中基于XML的IOC配置 一.简介 Spring的两大核心:IOC(DI)与AOP,IOC是反转控制,DI依赖注入 特点:轻量级.依赖注入.面向切面编程.容器. ...
- spring-第十八篇之spring AOP基于XML配置文件的管理方式
1.在XML配置文件中配置切面.切入点.增强处理.spring-1.5之前只能使用XML Schema方式配置切面.切入点.增强处理. spring配置文件中,所有的切面.切入点.增强处理都必须定义在 ...
- Spring3.2 中 Bean 定义之基于 XML 配置方式的源码解析
Spring3.2 中 Bean 定义之基于 XML 配置方式的源码解析 本文简要介绍了基于 Spring 的 web project 的启动流程,详细分析了 Spring 框架将开发人员基于 XML ...
- Spring中基于xml的AOP
1.Aop 全程是Aspect Oriented Programming 即面向切面编程,通过预编译方式和运行期动态代理实现程序功能的同一维护的一种技术.Aop是oop的延续,是软件开发中的 一个热点 ...
- 转-springAOP基于XML配置文件方式
springAOP基于XML配置文件方式 时间 2014-03-28 20:11:12 CSDN博客 原文 http://blog.csdn.net/yantingmei/article/deta ...
- spring的基于xml的AOP配置案例和切入点表达式的一些写法
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr ...
- Spring框架——基于XML/注解开发
IoC的实现方式有两种:XML配置文件.基于注解. MVC开发模式: Controller层 Service层 Repository层 Controller层调用Service,Service调用Re ...
- struts_20_对Action中所有方法、某一个方法进行输入校验(基于XML配置方式实现输入校验)
第01步:导包 第02步:配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app ...
- struts2视频学习笔记 22-23(基于XML配置方式实现对action的所有方法及部分方法进行校验)
课时22 基于XML配置方式实现对action的所有方法进行校验 使用基于XML配置方式实现输入校验时,Action也需要继承ActionSupport,并且提供校验文件,校验文件和action类 ...
- web.xml中配置Spring中applicationContext.xml的方式
2011-11-08 16:29 web.xml中配置Spring中applicationContext.xml的方式 使用web.xml方式加载Spring时,获取Spring applicatio ...
随机推荐
- Git 环境配置(详解版)
前言 Git下载官网:https://git-scm.com/downloads 本次使用Github为配置前提(Gitee步骤类似) 环境搭建 1.git安装好去GitHub上注册一个账号,注册好后 ...
- Spring-Bean的依赖注入的数据类型
Spring-Bean的依赖注入的数据类型 除了对象的引用可以注入,普通数据类型,集合等都可以在容器中进行注入 数据的三种数据类型 普通数据类型 引用数据类型 集合数据类型 普通数据类型 public ...
- [pandas]从多个文件中构建dataframe
按列从多个文件中构建 假设有两个csv文件,列不相同,需要整合为一个dataframe,使用glob模块: from glob import glob import pandas as pd # gl ...
- nflsoj 5926 素数环
题目非常简单,只需要判断相邻两个数的和是不是素数,素数的判断参考数论 不过要注意的一点是题目说的是一个环,所以首尾两个数的和也要是素数 我在输出的时候加上了 is_prime(path[n-1]+1) ...
- Typescript - 索引签名
1 索引签名概述 在 TypeScript 中,索引签名是一种定义对象类型的方式,它允许我们使用字符串或数字作为索引来访问对象的属性. 1.1 索引签名的定义和作用 索引签名通过以下语法进行定义: { ...
- 形象谈JVM-第四章-JVM内存结构
给我一个CPU,给我一块内存,我来执行一段代码. 我要如何分配呢? new User(); 这里有一个有一个User类,如果我要new出来User对象,必须先知道它长什么样子,我先搞一块区域出来,把U ...
- 《最新出炉》系列入门篇-Python+Playwright自动化测试-15-playwright处理浏览器多窗口切换
1.简介 浏览器多窗口的切换问题相比大家不会陌生吧,之前宏哥在java+selenium系列文章中就有介绍过.大致步骤就是:使用selenium进行浏览器的多个窗口切换测试,如果我们打开了多个网页,进 ...
- 淘宝详情api接口的应用
淘宝详情API接口是一个基于HTTP协议的接口服务,可用于获取淘宝商品的具体信息.下面将介绍如何调用淘宝详情API接口获取淘宝商品数据的步骤. 1.注册账号并创建应用 首先,我们需要进行账号注册.实名 ...
- Codeforces-1095E-Almost-Regular-Bracket-Sequence
题意 给定一个长度为 \(n\) 的小括号序列,求有多少个位置满足将这个位置的括号方向反过来后使得新序列是一个合法的括号序列.即在任意一个位置前缀左括号的个数不少于前缀右括号的个数,同时整个序列左右括 ...
- Go 语言内置类型全解析:从布尔到字符串的全维度探究
关注微信公众号[TechLeadCloud],分享互联网架构.云服务技术的全维度知识.作者拥有10+年互联网服务架构.AI产品研发经验.团队管理经验,同济本复旦硕,复旦机器人智能实验室成员,阿里云认证 ...