一、前言
在实际的开发中,我们可能需要去获取配置文件中的一些信息,本篇博客给大家介绍一下如何去实现这样一个需求。
二、单个字段信息的获取
如果需要获取信息的字段数量不多,那么我们可以选择使用@Value来实现我们的需求。
首先在配置文件中定义一些字段信息:
pullulates:
name: 大艺术家
sex: 男
nos: ${random.int}
这里需要注意:
在yml文件中,属性后一定要用单个空格隔开,例如:"name:"和“大艺术家”中间需要有一个空格间隔开。
属性的命名要避免关键字的冲突,如这里的编号要避免使用 no
接下来,在我们需要使用的地方,使用@Value将值注入到变量:
@Value("${pullulates.name}")
private String name;
@Value("${pullulates.sex}")
private String sex;
@Value("${pullulates.nos}")
private int nos;
然后,直接使用就可以啦~
@RestController
public class UserController {
@Value("${pullulates.name}")
private String name;
@Value("${pullulates.sex}")
private String sex;
@Value("${pullulates.nos}")
private int nos;
@RequestMapping(value="/")
public String hello() {
return "姓名:"+name+";性别:"+sex+";编号:"+nos;
}
}
浏览器显示如下:
姓名:大艺术家;性别:男;编号:696823726
三、多个字段信息
在实际的开发中,可能我们需要定义的字段非常多,这时候将这些信息全部定义在一个配置文件里会显得非常臃肿且难以维护,而且在每一个使用的地方都去建立对应的变量会大大提升我们的代码量。因此,在这种情况下,我们可以重新建立一个单独的配置文件,并将这些字段维护到一个bean中,在使用时,只需要引入这个bean就可以了!
首先,新建一个测试的配置文件pullulates.yml,放在config目录下:
project:
name: "pullulates"
version: "1.0.1"
copyright: "copyright © 2018-2019"
db: "mysql"
greeting: "欢迎来到 PULLULATES 系统"
然后,新建一个JavaBean Pullulates.java,并在pom添加依赖信息:
package top.pullulates.system.project;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 项目信息的实体类
*
*/
@Configuration
@ConfigurationProperties(prefix = "project")
@PropertySource("classpath:config/pullulates.yml")
@Component
public class Pullulates {
private String name;
private String version;
private String copyright;
private String db;
private String greeting;
@Override
public String toString() {
return "Pullulates{" +
"name='" + name + '\'' +
", version='" + version + '\'' +
", copyright='" + copyright + '\'' +
", db='" + db + '\'' +
", greeting='" + greeting + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getDb() {
return db;
}
public void setDb(String db) {
this.db = db;
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
注:
1. @ConfigurationProperties(prefix = "pullulates")
用于将配置文件的属性及值转为bean,它的内部定义了两个属性:prefix和value,prefix用于指定前缀,本例中指定的为 project,value为属性值。源码如下:
package org.springframework.boot.context.properties;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {
@AliasFor("prefix")
String value() default "";
@AliasFor("value")
String prefix() default "";
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}
这里需要注意的是版本兼容问题。在1.5及之前的版本,还提供了location属性,用于指定配置文件,但是在1.5之后废除了。
@PropertySource("classpath:config/pullulates.yml")
用于指定配置文件,作用类似于上文中的location,注意这里加了config。
最后,需要在程序入口处添加注解@EnableConfigurationProperties({Pullulates.class}),如果有多个配置文件,则在后面添加,以逗号隔开,如@EnableConfigurationProperties({Pullulates.class,User.class}),这里默认的配置文件application.yml是不需要指定的,在未指定的情况下,默认从application.yml中读取:
@SpringBootApplication
@EnableConfigurationProperties({Pullulates.class})
public class PullulatesApplication {
public static void main(String[] args) {
SpringApplication.run(PullulatesApplication.class, args);
}
}
接下来,只需要在使用场景中注入bean就可以了。
@RestController
public class UserController {
@Autowired
private Pullulates pullulates;
@RequestMapping(value="/")
public String hello() {
return pullulates.toString();
}
}
启动项目,访问浏览器,显示:
NULL,没错,就是NULL,一开始我也是百思不得其解,直到我把配置文件的格式改为".properties":
project.name=pullulates
project.version=1.0.1
project.copyright=copyright © 2018-2019
project.db=mysql
project.greeting=欢迎来到 PULLULATES 系统
然后,就可以了! 浏览器显示:
Pullulates{name='pullulates', version='1.0.1', copyright='copyright © 2018-2019', db='mysql', greeting='欢è¿æ¥å° PULLULATES ç³»ç»'}
PropertySource这个注解,该注解不支持yml文件加载!一般情况下,我们可以顺着官方的意思,使用properties配置文件,但是如果真的偏爱yml配置文件,那该如何呢?
既然PropertySource不支持yml格式,那我们就不用这个注解,我们可以配置一个bean,用于获取该配置文件的内容。接下来,新建一个新的yml配置文件student.yml:
student:
name: "pullulate"
age: 18
新建Student.java:
@Configuration
@ConfigurationProperties(prefix = "student")
@Component
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
最关键的一步,新建一个Yml Bean:
@Configuration
public class YmlConfig {
// 加载YML格式自定义配置文件
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
// yaml.setResources(new FileSystemResource("application-cat.yml"));// File引入
yaml.setResources(new ClassPathResource("config/student.yml"));// class引入
configurer.setProperties(yaml.getObject());
return configurer;
}
}
运行项目,浏览器显示:
姓名:pullulate;年龄:18
PropertySource接口源码里,我们可以看到:
/**
* A specific character encoding for the given resources, e.g. "UTF-8".
* @since 4.3
*/
String encoding() default "";
因此,我们需要在注解里指定编码方式:
@PropertySource(value = "classpath:config/pullulates.properties",encoding = "utf-8")
运行项目,浏览器显示:
Pullulates{name='pullulates', version='1.0.1', copyright='copyright © 2018-2019', db='mysql', greeting='欢迎来到 PULLULATES 系统'}
这里,我们是从源码推测出来解决问题的方法,在实际开发中,这也是一个很好的思路,不用事事百度。
PS:在application.properties中的各个参数之间也可以直接引用来使用,例如:
project.name=pullulates
project.version=1.0.1
project.copyright=copyright © 2018-2019
project.db=mysql
project.greeting=欢迎来到 ${project.name} 系统
四、配置文件中random的使用
配置文件中${random} 可以用来生成各种不同类型的随机值,从而简化了代码生成的麻烦,例如 生成 int 值、long 值或者 string 字符串。
${random.value}
${random.int}
${random.long}
${random.uuid}
${random.int(10)}
${random.int[1024,65536]}
OK,本篇博客基本结束了。这里其实还有一个可拓展的方面,不过鉴于网上有很多的解决办法,就不在这里说了。强求面面俱到,有时候,反而效率会变低。这里还是贴上一个链接,是关于如何读取自定义配置文件的,比如json格式的配置文件。