JAVA全系列 教程
3762个小节阅读:7090k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
util命名空间从Spring Framework 2.0开始就有了。但是作为Spring框架支持的命名空间,还是有必要给小伙伴们介绍一下。
util命名空间主要的作用简化定义集合类型Bean、常量类型Bean的语法。实现快速给特定类型定义为Bean。像这种给特定类型单独定义成Bean是为了这个类型值实现复用,其他Bean可以通过ref直接引用,但是util命名空间的作用是简化定义的语法,而不是为了复用。
想要使用util命名空间,必须在Spring框架配置文件中导入对应的xsd文件路径及命名空间。
xxxxxxxxxx
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
https://www.springframework.org/schema/util/spring-util.xsd">
</beans>
导入命名空间后,可以发现util一共支持6个标签,分别代表的含义:
先创建一个类,类中包含一个静态属性com.bjsxt.pojo.MyUtil
xxxxxxxxxx
public class MyUtil {
public static String NAME="smallmming";
}
当我们想要把上面这个静态变量定义为一个Bean时,必须借助FieldRetrievingFactoryBean才能定义。
xxxxxxxxxx
<bean id="myName" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField" value="com.bjsxt.pojo.MyUtil.NAME"></property>
</bean>
上面的写法也有一种简写方式
xxxxxxxxxx
<bean id="com.bjsxt.pojo.MyUtil.NAME" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"></bean>
简写方式已经比较简单了,但是最简单的方式还是使用util命名空间。不需要再去记忆FieldRetrievingFactoryBean这个类。
xxxxxxxxxx
<util:constant static-field="com.bjsxt.pojo.MyUtil.NAME"></util:constant>
如果定义完成后,想要把常量Bean注入到其他类属性中
先定义一个类com.bjsxt.pojo.Demo
xxxxxxxxxx
public class Demo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Demo{" +
"name='" + name + '\'' +
'}';
}
}
修改配置文件,给util:constant定义一个id,然后让Demo的name属性ref这个id值。
xxxxxxxxxx
<util:constant static-field="com.bjsxt.pojo.MyUtil.NAME" id="myUtilName"></util:constant>
<bean id="demo" class="com.bjsxt.pojo.Demo">
<property name="name" ref="myUtilName"></property>
</bean>
编写测试
xxxxxxxxxx
@Test
void util(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext5.xml");
Demo demo = ac.getBean("demo", Demo.class);
System.out.println(demo);
}