有效的减少硬编码(将配置信息直接写入Java代码中)
当应用程序的运行环境发生改变时,只需要修改属性文件,而不需要改变源码.提高了运维人员操作的便利性
以db.properties文件为例
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/DBName?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
mysql.user=root
mysql.password=010220
可以使用@PropertySource进行属性文件的加载
@PropertySource的配置项有:
package com.bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
/**
* @author Una
* @date 2022/8/9 20:07
* @description:
*/
@PropertySource(value = {"classpath:db.properties"},ignoreResourceNotFound = true)
public class PropertiesScan {
}
测试时使用getEnvironment().getProperty()可获得
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.Assert.*;
/**
* @author Una
* @date 2022/8/9 20:08
* @description:
*/
public class PropertiesScanTest {
@Test
public void showProperties(){
AnnotationConfigApplicationContext aac=new AnnotationConfigApplicationContext(PropertiesScan.class);
String root=aac.getEnvironment().getProperty("mysql.root");
System.out.println(root);
}
}
在配置文件中直接加入
<context:property-placeholder location="classpath:database-config.properties" ignore-resource-not-found="true"/>