目录
spring标签
spring配置文件中标签分为默认标签和自定义标签;
默认标签:不需要额外导入其他命名空间约束的标签
自定义标签:需要额外导入其他命名空间约束的标签
补充:XML Schema语言是用来定义描述xml文档结构的,简称xsd
spring部分默认标签如下:
标签名 | 作用 |
---|---|
<beans> | 作为xml配置的根标签 |
<bean> | 作为配置类相关的标签 |
<import> | 导入外部资源的标签 |
使用beans标签配置多环境
<?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">
<beans profile="dev">
<bean class="com.cc.entity.Aaaa" id="aaaa-dev"></bean>
</beans>
<beans profile="pro">
<bean class="com.cc.entity.Aaaa" id="aaaa-pro"></bean>
</beans>
<beans profile="test">
<bean class="com.cc.entity.Aaaa" id="aaaa-test"></bean>
</beans>
</beans>
public class Main {
public static void main(String[] args) {
// 设置哪套环境开启生效 这里表示dev环境生效
System.setProperty("spring.profiles.active","dev");
// 我要找容器要对象,首先得有容器对象 ClassPathXmlApxxxxx
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");// 生成等号左边的代码的快捷键是alt键+回车
// 通过容器对象调用getbean方法拿我要的对象,并且通过参数指定要的对象名称
Object bean = app.getBean("aaaa-dev");
System.out.println(bean);
}
}
此时改成test环境生效,再次运行:
System.setProperty("spring.profiles.active","text");
产生报错,说明dev环境没被解析,所以无法获取。
import引入其他配置文件
import标签可以帮我们引入外部的资源,包括:其他配置文件、类、文件、网址;
示例:
准备了两个类和两个配置文件,其中一个配置文件使用import导入了另外一个配置文件:
<?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 class="com.cc.test.A" id="a"></bean>
</beans>
<?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 class="com.cc.test.C" id="c"></bean>
<import resource="testTwo.xml"></import>
</beans>
在测试类中,仅解析一个xml文件,然后使用getBean获取id为a和c的bean;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("test.xml");
Object bean = app.getBean("a");
Object bean1 = app.getBean("c");
System.out.println(bean);
System.out.println(bean1);
}
}
结果为两个bean都能成功获取
引入自定义标签
引入自定义标签的步骤
- 导入jar包
- 在bean.xml文件中配置环境
引入schema文件的具体步骤
1、查看schema文档,找到根元素,在xml中写出来
2、根元素来自哪个命名空间。使用xmlns指令来声明(命名空间的作用:它指的是一个环境,所用的标签来自于哪个环境定义的) xmlns=xml name space
3、声明引入的名称空间跟哪个xsd文件对应
4、声明schemaLocation哪里来的,一般都是某个标准(写法上都是先写命名空间+具体文件的位置【他们是一对】)
示例:
以dubbo为例,首先导入jar包:
引入schema写法:
这样就能够使用dubbo提供的标签了: