关于外部化配置其实不用多说,springboot太常见了,把内部配置转变成properties或是yml或是其他形式,更方便的进行配置和管理。
关于运用场景
关于外部化配置的运用其实都很常见,主要有:
-
xml Bean定义的属性占位符
Spring关于xml外部化配置
haozi-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 属性占位符配置-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- Properties 文件 classpath 路径 -->
<property name="location" value="classpath:/META-INF/default.properties"/>
<!-- 文件字符编码 -->
<property name="fileEncoding" value="UTF-8"/>
</bean>
<!-- Haozi Bean -->
<bean id="haozi"
class="com.haozi.externalizated.configuration.domain.Haozi">
<property name="id" value="${haozi.id}"/>
<property name="name" value="${haozi.name}"/>
</bean>
</beans>
default.peoperties
haozi.id = 1
haozi.name = 耗子肉
实体类:
public class Haozi {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Haozi{id=" + id + ", name='" + name + "'}";
}
}
引导类:
/**
* spring xml配置占位符引导类
*/
public class SpringXmlConfigBootstrap {
public static void main(String[] args) {
String[] locations = {"META-INF/spring/haozi-context.xml"};
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(locations);
Haozi haozi = applicationContext.getBean("haozi", Haozi.class);
System.out.println("用户对象 : " + haozi);
// 关闭上下文
applicationContext.close();
}
}
调整为SpringBoot
将META-INF/default.properties改成application.properties
user.id = 1
user.name = haozirou
haozi-context.xml(故意将haozi变成了user)
<?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">
<!-- User Bean -->
<bean id="user"
class="com.haozi.externalizated.configuration.domain.Haozi">
<property name="id" value="${user.id}"/>
<property name="name" value="${user.name}"/>
</bean>
</beans>
引导类
@ImportResource("META-INF/spring/haozi-context.xml") // 加载 Spring 上下文 XML 文件
@EnableAutoConfiguration
public class SpringbootXmlConfigBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(SpringbootXmlConfigBootstrap.class)
.web(WebApplicationType.NONE) // 非 Web 应用
.run(args);
Haozi haozi = context.getBean("user", Haozi.class);
System.out.println("用户对象 : " + haozi);
// 关闭上下文
context.close();
}
}
运行结果出现了差异
如果把haozi换成user,这里的name就不是properties里面的了。
通过查看springboot文档
通过执行顺序可以知道,java的系统配置(9)会优