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 ...
随机推荐
- Avalonia项目打包安装包
Avalonia项目打包安装包 要将 Avalonia 项目打包成安装包,你可以使用 Avalonia 发布工具来完成 1.创建一个发布配置文件 在你的 Avalonia 项目中,创建一个发布配置文件 ...
- 代码随想录算法训练营第三天| LeetCode 203.移除链表元素(同时也对整个单链表进行增删改查操作) 707.设计链表 206.反转链表
203.移除链表元素 题目链接/文章讲解/视频讲解::https://programmercarl.com/0203.%E7%A7%BB%E9%99%A4%E9%93%BE%E8%A1 ...
- 【技术积累】Linux中的命令行【理论篇】【一】
7z命令 命令介绍 7z命令是Linux系统中的一个压缩和解压缩工具,它可以用来创建.压缩和解压缩7z格式的文件.7z是一种高压缩率的文件格式,通常比其他常见的压缩格式(如zip和gzip)具有更高的 ...
- 管于pyinstaller 打包完成后不能运行的问题
方案一: 进入项目路径,在cmd窗口输入python 文件名.之后查看结果,看是否有模块未安装,或者是未导入模块.因为pyinstaller打包时,是按照被打包文件上的导入的库名进行打包的,所以需要将 ...
- word中查找替换不能使用 解决方案
打开查找,然后点更多,最下面点不限定格式
- 让nodejs开启服务更简单--express篇
上一篇文章说到,nodejs获取客户端请求需要我们自己去处理请求参数.请求方式等,而在express框架内部集成了很多好用的方法,我们不需要从0开始编写各种处理逻辑,这样可以极大提高我们的开发效率~ ...
- [mysql]MGR简介与部署
前言 MySQL Group Replication,简称MGR,是MySQL官方于2016年推出的一个全新的高可用解决方案,采用Paxos分布式一致性协议作为高可用和一致性解决方案.在MGR之前的高 ...
- Windows安装hexo并配置nginx
前言 Hexo是一款基于NodeJS的静态博客框架,依赖少且易于安装使用,可以方便地生成静态网页. 本文记录Windows安装hexo,配置第三方主题Fluid,并配置nginx的全过程. nodej ...
- Linux cpu 亲缘性 绑核
前言 https://www.cnblogs.com/studywithallofyou/p/17435497.html https://www.cnblogs.com/studywithallofy ...
- GIT提交修改的项目到远程仓库
1.在项目目录下右键选择Git Bash. 2.执行提交命令三部曲 git add . //文件-暂存区,即将所有新增的文件添加到提交索引中,,add后面是"空格 点"就表示当前目 ...