Spring context:property-placeholder
教程展示了如何使用context:property-placeholder
标记来外部化 Spring 应用中的属性。
Spring 是用于创建企业应用的流行 Java 应用框架。
Spring 的context:property-placeholder
context:property-placeholder
标签用于外部化单独文件中的属性。 它会自动配置PropertyPlaceholderConfigurer
,从而替换${}
占位符,这些占位符针对指定的属性文件(作为 Spring 资源位置)进行解析。
Spring context:property-placeholder
示例
该应用使用context:property-placeholder
来配置数据源的属性。
这是项目结构。
pom.xml
在pom.xml
文件中,我们具有基本的 Spring 依赖项spring-core
,spring-context
,spring-jdbc
和日志记录logback-classic
依赖项。
exec-maven-plugin
用于在命令行上从 Maven 执行 Spring 应用。
resources/logback.xml
logback.xml
是 Logback 日志库的配置文件。
resources/database.properties
这些值在database.properties
文件中外部化。 这种方法比将值直接放入 XML 文件中更为灵活。
resources/my-beans.xml
context:property-placeholder
指定属性文件的位置; 在我们的例子中,它是任何类路径目录中的database.properties
文件。
定义了dataSource
bean。 它通过${}
语法从属性文件中获取其值。
com/zetcode/Application.java
这是主要的应用类。 它检索dataSource
bean 并打印其属性。
我们运行该应用。
在本教程中,我们展示了如何使用context:property-placeholder
来外部化属性。