在开发的过程中,配置文件往往就是那些属性(properties)文件,比如使用properties文件配置数据库文件,又如database-config.properties
  代码清单:database-config.properties

jdbc.database.driver=com.mysql.cj.jdbc.Driver
jdbc.database.url=jdbc:mysql://localhost:3306/springmvc?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true
jdbc.database.username=root
jdbc.database.password=123456

  使用属性文件可以有效地减少硬编码,很多时候修改环境只需要修改配置文件就可以了,这样能够有效提高运维人员的操作便利性,所以使用properties文件是十分常见的场景。在Spring中也可以通过注解或者XML的方式进行加载属性文件

使用注解方式加载属性文件

  Spring提供了注解@PropertySource来加载属性文件,了解它的配置项。
  •name:字符串,配置这次属性配置的名称。
  •value:字符串数组,可以配置多个属性文件。
  •ignoreResourceNotFound:boolean值,默认为false,其含义为如果找不到对应的属性文件是否进行忽略处理,由于默认值为false,所以在默认的情况下找不到对应的配置文件会抛出异常。
  •encoding:编码,默认为""。

  代码清单:在Spring环境中使用属性文件Java配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration
// @ComponentScan(basePackages = {"com.ssm.chapter10.annotation"})
@ImportResource({"classpath:ssm/chapter10/spring-dataSource.xml"})
@PropertySource(value = {"classpath:ssm/chapter10/database-config.properties"})
public class ApplicationConfig2 {
}

  代码清单:测试加载属性

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig2.class);
String url = context.getEnvironment().getProperty("jdbc.database.url");
System.out.println(url);

  Spring中是没有解析属性占位符的能力,Spring推荐使用一个属性文件解析类进行处理,它就是PropertySources Placeholder-Configurer,使用它就意味着允许Spring解析对应的属性文件,并通过占位符去引用对应的配置。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration
// @ComponentScan(basePackages = {"com.ssm.chapter10.annotation"})
@ImportResource({"classpath:ssm/chapter10/spring-dataSource.xml"})
@PropertySource(value = {"classpath:ssm/chapter10/database-config.properties"})
public class ApplicationConfig2 { /**
* 作用是为了让Spring能够解析属性占位符,
*/
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
} }

  引用已经定义好的配置,这里可以使用注解@Value和占位符

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component; import javax.sql.DataSource;
import java.util.Properties; @Component
public class ProfileDataSource { @Value("${jdbc.database.driver}")
private String driver = null;
@Value("${jdbc.database.url}")
private String url = null;
@Value("${jdbc.database.username}")
private String username = null;
@Value("${jdbc.database.password}")
private String password = null; @Bean(name = "dataSource2")
public DataSource getDataSource() {
Properties props = new Properties();
props.setProperty("driver", driver);
props.setProperty("url", url);
props.setProperty("username", username);
props.setProperty("password", password);
DataSource dataSource = null;
try {
dataSource = (DataSource) BasicDataSourceFactory.createDataSource(props);
System.out.println("-----dataSource2 init-----");
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
} }

使用XML方式加载属性文件

  也可以使用XML方式进行加载属性文件,它只需要使用<con-text:property-placeholder>元素加载一些配置项即可。
  代码清单:通过XML加载属性文件

<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"> <context:component-scan base-package="com.ssm.chapter10.annotation"/> <!--<import resourse="spring-datasource.xml"/>--> <!--<context:property-placeholder ignore-resource-not-found="true" location="classpath:ssm/chapter10/database-config.properties"/>--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!--字符串数组,可配置多个属性文件-->
<property name="locations">
<array>
<value>classpath:ssm/chapter10/database-config.properties</value>
<value>classpath:log4j.properties</value>
</array>
</property>
<property name="ignoreResourceNotFound" value="false"/>
</bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springmvc?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean> </beans>

spring 加载属性(properties)文件的更多相关文章

  1. 【转载】加密Spring加载的Properties文件

    目标:要加密spring的jdbc配置文件的密码口令. 实现思路:重写加载器的方法,做到偷梁换柱,在真正使用配置之前完成解密. 1.扩展 package com.rail.comm; import j ...

  2. 解密Spring加载的Properties文件

    Spring的框架中,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类可以将.properties(key ...

  3. SpringMVC加载配置Properties文件的几种方式

    最近开发的项目使用了SpringMVC的框架,用下来感觉SpringMVC的代码实现的非常优雅,功能也非常强大, 网上介绍Controller参数绑定.URL映射的文章都很多了,写这篇博客主要总结一下 ...

  4. 【Java Web开发学习】Spring加载外部properties配置文件

    [Java Web开发学习]Spring加载外部properties配置文件 转载:https://www.cnblogs.com/yangchongxing/p/9136505.html 1.声明属 ...

  5. Eclipse下SpringBoot没有自动加载application.properties文件

    Eclipse内创建SpringBoot项目,在java/main/resources文件夹下面创建application.properties配置文件,SpringApplication.run后发 ...

  6. spring加载属性(properties)文件

    一.注解方式加载 jdbc.driver=org.mariadb.jdbc.Driver jdbc.url=jdbc:mariadb://localhost:3306/kt jdbc.user=roo ...

  7. spring学习 十六 spring加载属性文件

    第一步:创建一个properties文件,以数据库链接作为实例db.properties jdbc.url=jdbc:mysql://192.168.153.128:3306/mybaties?cha ...

  8. spring加载属性配置文件内容

    在spring中提供了一个专门加载文件的类PropertyPlaceholderConfigurer,通过这个类我们只需要给定需要加载文件的路径就可以 通过该类加载到项目,但是为了后面在程序中需要使用 ...

  9. Java实现动态加载读取properties文件

    问题: 当我们使用如下语句加载.properties时: ClassLoader classLoader = this.getClass().getClassLoader(); Properties ...

随机推荐

  1. c99的新功能

    在ANSI的标准确立后,C语言的规范在一段时间内没有大的变动,然而C++在自己的标准化创建过程中继续发展壮大.<标准修正案一>在1994年为C语言创建了一个新标准,但是只修正了一些C89标 ...

  2. 题解 UVa10780

    题目大意 多组数据,每组数据给定两个整数 \(m,n\),输出使 \(n\%m^k=0\) 的最大的 \(k\).如果 \(k=0\) 则输出Impossible to divide. 分析 计数水题 ...

  3. MySql数据库导出完整版(导出数据库,导出表,导出数据库结构)

    MySql数据库导出完整版(导出数据库,导出表,导出数据库结构) 用MySqlCE导出数据库脚本时,如数据库中包含中文内容,则导出异常. 现在可以通过mysqldump.exe直接导出数据库脚本步骤如 ...

  4. 非自增编号字段,避免生成重复编号(以pdfNo编号为例)RedisLock/ReadLock

    非自增编号字段,避免生成重复编号(以pdfNo编号为例) 有个场景,用户查询延误航班信息,然后生产一个编号,默认第一个编号是1000001,其后新增的编号默认自增加1.每次有人来查延误信息,如果延误信 ...

  5. SQL 删除字段 增加字段

    SQL增加字段需要用到sql语句 ALTER TABLE 加(表格名称) ADD 加(字段名称) 加(字段类型)实例:ALTER TABLE T_Basic ADD SEODescription Nv ...

  6. 连接linux的几款工具 简介

    1.Putty --支持ppk,pub格式密码连接 --支持centos --支持windows操作系统安装,网上去下载直接可以使用,免费的 安装文件在我的百度网盘:putty 安装后如下: load ...

  7. arts打开第11周

    给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写. 说明:本题中,我们将空字符串定义为有效的回文串. 示例 1: 输入: "A man, a plan, a c ...

  8. Flutter扫码识别二维码内容

    前面一篇写了生成二维码图片,这篇来写使用相机扫描识别二维码 识别二维码需要用到插件 barcode_scan 首先在 pubspec.yaml 文件中添加以下依赖,添加依赖后在 pubspec.yam ...

  9. PHP的ini_set函数用法

    PHP   ini_set用来设置php.ini的值,在函数执行的时候生效,脚本结束后,设置失效.无需打开php.ini文件,就能修改配置,对于虚拟空间来说,很方便. 函数格式:string   in ...

  10. 安装adbyby

    搞得那么麻烦干什么,助人就要直接点嘛请用 Xshell 连接你的路由 1.安装curlopkg update && opkg install curl 2.创建相关文件夹(如已经安装a ...