springboot获取配置文件属性的值
1.学前了解
写这篇博客的原因就是,我接触了好多springboot配置文件属性值的方法,每次都是百度,这次把好好的总结整理一下,第一印象就是@Value注解,还有使用Hutool工具类,能获取到resources目录下的配置文件
2.使用Hutool获取springboot项目/src/main/resources目录下的配置文件信息
hutool官网地址: https://www.hutool.cn/
说明:
如果之前没有用hutool工具类的朋友可以使用以下,挺好用的一个国产开源的java工具集
使用方法:
直接在pom.xml里面引入相关依赖,直接开箱即用
2.1引入hutool的依赖
<!-- 引入Hutool工具类,是一个国产开源的java工具集,很好用 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.2</version>
</dependency>
2.2 写测试的配置文件
说明:
我写了两个properties的配置文件
1.在src/main/resources目录下,文件名为my.properties
2.在src/main/resources/properties目录下,文件名为userinfo.properties
properties是我新建的文件夹
- my.properties内容如下
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8
db.username=root
db.password=root
- userinfo.properties内容如下
username=shaoming
password=root
javaversion=1.8
address=nanjing
2.3 测试
package com.shaoming.test;
import cn.hutool.core.io.resource.ClassPathResource;
import com.shaoming.config.util.MyUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.Properties;
/**
* @Auther: shaoming
* @Date: 2020/9/13 12:53
* @Description:
*/
@SpringBootTest
public class MyTest {
/**
* hutool工具类,获取/src/mian/resource/目录下文件的值
*/
@Test
public void testGetPropertiesProperty(){
ClassPathResource classPathResource = new ClassPathResource("my.properties");
Properties properties = new Properties();
try {
properties.load(classPathResource.getStream());
//直接打印my.properties文件的信息
System.out.println(properties);
//获取key为username的属性的值
System.out.println(properties.get("username"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
控制台打印结果
{txserverip=119.45.152.156, url=localhost:3306, passworld=root, username=root}
root
*/
/**
* hutool工具类,获取/src/mian/resource/目录下文件的值
*/
@Test
public void testGetUpPropertiesProperty(){
ClassPathResource classPathResource = new ClassPathResource("/properties/userinfo.properties");
Properties properties = new Properties();
try {
properties.load(classPathResource.getStream());
System.out.println(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
控制台打印结果
{address=nanjing, password=root, javaversion=1.8, username=shaoming}
*/
可以获取到properties文件的内容
补充一个小知识点:
properties的key-value是无序的
3.少量配置信息的情形,@Value注解的使用
说明:
@Value作用:注入 Spring boot application.properties 配置的属性的值。
如果配置文件时application.yml,同理
使用@Value的前提:
pojo要在spring容器类,所以在对应的类上加上注解@Component
@Value语法:
@Value("${xxx}")
3.1在application.propertis定义相关的属性
classname=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8
db.username=root
db.password=root
3.2 定义pojo类,配置属性注入到pojo类的属性
package com.shaoming.component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Auther: shaoming
* @Date: 2020/9/13 16:47
* @Description:
*/
@Component//这个注解的作用是把当前类交给spring容器
public class MyClusTomBean {
@Value("${classname}")
private String calssName;
@Value("${db.username}")
private String userName;
//提供get/set/toString方法
public String getCalssName() {
return calssName;
}
public void setCalssName(String calssName) {
this.calssName = calssName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "MyClusTomBean{" +
"calssName='" + calssName + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
3.3测试
@SpringBootTest
public class MyTest {
//从容器中获取MyClusTomBean
@Autowired
private MyClusTomBean myClusTomBean;
@Test
public void testValue(){
//获取calssName的值
System.out.println(myClusTomBean.getCalssName());
//获取userName属性的值
System.out.println(myClusTomBean.getUserName());
//打印myClusTomBean实体类的信息
System.out.println(myClusTomBean);
}
}
4.多个配置信息的情形,@ConfigurationProperties使用
说明:
如果这样一个个去使用 @Value 注解引入相应的微服务地址的话,太过于繁
琐,也不科学。所以使用@ConfigurationProperties这个注解
用法:
@ConfigurationProperties(prefix = “前缀”)
前提:
1.使用@ConfigurationProperties注解的前提时当前类需要交给spring容器管理
2.引入依赖
org.springframework.boot spring-boot-configuration-processor true
3.1在application.propertis定义相关的属性
classname=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8
db.username=root
db.password=root
db.number=123
3.2 定义pojo类,配置属性注入到pojo类的属性
package com.shaoming.component;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Auther: shaoming
* @Date: 2020/9/13 21:32
* @Description:
db.username=root
* db.password=root
* db.number=123
*/
/**
* 说明:使用@ConfigurationProperties
* 需要引入依赖
* spring-boot-configuration-processor
*/
@ConfigurationProperties(prefix = "db")
//使用@ConfigurationProperties注入属性,需要把该类交给spring容器管理
@Component
public class ManyPropertyBean {
private String username;
private String password;
private Integer number;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
@Override
public String toString() {
return "ManyPropertyBean{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", number=" + number +
'}';
}
}
3.3测试
package com.shaoming.test;
import cn.hutool.core.io.resource.ClassPathResource;
import com.shaoming.component.ManyPropertyBean;
import com.shaoming.component.MyClusTomBean;
import com.shaoming.util.MyUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.Properties;
/**
* @Auther: shaoming
* @Date: 2020/9/13 12:53
* @Description:
*/
@SpringBootTest
public class MyTest {
@Autowired
private ManyPropertyBean manyPropertyBean;
@Test
public void testConfigurationProperties(){
//获取各个属性的值
System.out.println(manyPropertyBean.getNumber());
//测试数值类型的值时相对应的数值类型,不是String
System.out.println(manyPropertyBean.getNumber().getClass());
System.out.println(manyPropertyBean.getUsername());
System.out.println(manyPropertyBean.getPassword());
//打印manyPropertyBean这个类的信息
System.out.println(manyPropertyBean);
}
}
/**
控制台打印:
123
class java.lang.Integer
root
root
ManyPropertyBean{username='root', password='root', number=123}
*/
5.指定配置文件为属性赋值(通用)@PropertySource注解使用
说明:
这个方法类似于Hutool工具类操作resource目录下的properties配置文件,比较有通用性
使用:
@PropertySource(“classpath:/properties/student.properties”)要配合@Value注解使用
@Value之前说了,把配置文件属性值注入给pojo属性
前提:
1.当前类交给spring容器管理
2.引入相关依赖
org.springframework.boot spring-boot-configuration-processor true
3.1在src/main/resources/properties目录下,文件名为student.properties
其中properties是自己定义的目录,不是springboot自带的
student.id=1001
student.name=zhangsan
3.2定义pojo类,配置属性注入到pojo类的属性
package com.shaoming.component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @Auther: shaoming
* @Date: 2020/9/13 21:46
* @Description:
*/
//spring容器启动时加载指定的配置文件
@PropertySource("classpath:/properties/student.properties")
@Component
public class PropertySourceBean {
@Value("${student.id}")
private Integer id;
@Value("${student.name}")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "PropertySourceBean{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
3.3 测试
@Test
public void testPropertySource(){
//获取各个属性的值
System.out.println(propertySourceBean.getId());
//测试数值类型的值时相对应的数值类型,不是String
System.out.println(propertySourceBean.getId().getClass());
System.out.println(propertySourceBean.getName());
//打印propertySourceBean信息
System.out.println(propertySourceBean);
}
/**
* 控制台打印:
* 1001
* class java.lang.Integer
* zhangsan
* PropertySourceBean{id=1001, name='zhangsan'}
*/
总结
一共有四种方法(只是我知道,应该还有别的方法)
- hutool的ClassPathResource
- @Value
- @ConfigurationProperties
- @PropertySource+@Value
补充:hutool的操作可以封装成工具类ClassPathResourceUtil
作用:传递properties类型配置文件的路径,返回配置文件信息
package com.shaoming.util;
import cn.hutool.core.io.resource.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @Auther: shaoming
* @Date: 2020/9/13 22:02
* @Description:
*/
public class ClassPathResourceUtil {
private static ClassPathResource classPathResource = null;
private static InputStream stream=null;
/**
*
* @param propertiesPath springboot配置文件的路径
*/
public static Properties getResourcesPropertiesInfo(String propertiesPath) {
classPathResource = new ClassPathResource(propertiesPath);
Properties properties = new Properties();
InputStream stream=null;
try {
//获取输入流
stream = classPathResource.getStream();
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}finally {
// properties.clear();
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return properties;
}
}