Hi ! 我是小小,今天是本周的第三篇,Spring Boot 中使用@Value读取配置文件

配置文件配置

直接配置 在src/main/resources下添加配置文件,application.properties 修改端口号等。

#端口号
server.port=8089

如果要是开发环境,测试环境,等环境配置需要做如下配置 在src/main/resources下添加,application-pro.properties, application-dev.properties 和 application.properties 三个文件, 内容如下 application.properties

spring.profiles.active=dev

application-pro.properties

#端口号
server.port=80
#自定义端口号读取
my.name=pzr.dev

application-dev.properties

#端口号
server.port=8089
#自定义端口号读取
my.name=pzr.pro

单spplication.properties 设置spring.profiles.active=dev的时候,说明指定使用application-dev.properties 文件进行配置。

配置文件参数读取

注解方式读取

@PropertySource

@PropertySource 配置文件路径设置,在类上添加注解,如果在默认路径下可以不添加该注解。

@PropertySource({"classpath:config/my.properties","classpath:config/config.properties"})
public class TestController

@Value 属性名,在属性名上添加注解

@Value("${my.name}")
private String myName;

配置文件中配置集合类(Map,List) @Value 注入map,List

yaml格式

@Value("#{'${list}'.split(',')}")
private List<String> list;

@Value("#{${maps}}")
private Map<String,String> maps;

@Value("#{${redirectUrl}}")
private Map<String,String> redirectUrl;

配置文件

list: topic1,topic2,topic3
maps: "{key1: 'value1', key2: 'value2'}"
redirectUrl: "{sso_client_id: '${id}',sso_client_secret: '${secret}',redirect_url: '${client.main.url.default}'}"

举俩例子

例子一

配置文件application.properties

spring.application.name=springbootdemo
server.port=8080
mail.username=application-duan
mail.password=application-duan123456

启动类

package com.dxz.property5;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class TestProperty5 {

public static void main(String[] args) {
//SpringApplication.run(TestProperty1.class, args);
new SpringApplicationBuilder(TestProperty5.class).web(true).run(args);

}
}

测试类

package com.dxz.property5;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/task")
//@PropertySource("classpath:mail.properties")
public class TaskController {

@Value("${mail.username}")
private String userName;

@Value("${mail.password}")
private String password;

@RequestMapping(value = { "/", "" })
public String hellTask() {
System.out.println("userName:" + userName);
System.out.println("password:" + password);
return "hello task !!";
}

}

结果

userName:application-duan
password:application-duan123456

例子二

使用 @Value + @PropertySource读取其他配置文件,多个内容 读取mail.properties 配置

package com.dxz.property5;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/task")
@PropertySource("classpath:mail.properties")
public class TaskController {
@Value("${mail.smtp.auth}")
private String userName;

@Value("${mail.from}")
private String password;

@RequestMapping(value = { "/", "" })
public String hellTask() {
System.out.println("userName:" + userName);
System.out.println("password:" + password);
return "hello task !!";
}

}

结果

userName:false
password:me@localhost

按照对象映射方式读取

  1. 首先建立对象与配置文件映射关系
  2. 方法中使用自动注入方式,对象注入,调用get获取属性值 测试类
package com.dxz.property6;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/task")
@PropertySource({ "classpath:mail.properties", "classpath:db.properties" })
public class TaskController {

// 在application.properties中的文件,直接使用@Value读取即可,applicarion的读取优先级最高
@Value("${mail.username}")
private String myName;

// 如果多个文件有重复的名称的属性话,最后一个文件中的属性生效
@Value("${mail.port}")
private String port;

@Value("${db.username}")
private String dbUserName;

@Autowired
ObjectProperties objectProperties;

@RequestMapping("/test")
@ResponseBody
String test() {
String result = "myName:" + myName + "n port:" + port + "n dbUserName:" + dbUserName + "n objectProperties:"
+ objectProperties;
System.out.println("result:=" + result);
return result;
}


}

启动类

package com.dxz.property6;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class TestProperty6 {

public static void main(String[] args) {
//SpringApplication.run(TestProperty1.class, args);
new SpringApplicationBuilder(TestProperty6.class).web(true).run(args);

}
}

ObjectProperties.java

package com.dxz.property6;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
* 配置文件映射对象
* @author DELL
*/
@Component
@PropertySource("classpath:config/object.properties")
@ConfigurationProperties(prefix = "obj")
public class ObjectProperties {

private String name;
private String age;
// 集合必须初始化,如果找不到就是空集合,会报错
private List<String> className = new ArrayList<String>();

public List<String> getClassName() {
return className;
}

public void setClassName(List<String> className) {
this.className = className;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

@Override
public String toString() {
return "ObjectProperties [name=" + name + ", age=" + age + ", className=" + className + "]";
}


}

object.properties

#自定义属性读取
obj.name=obj.name
obj.age=obj.age
obj.className[0]=obj.className[0]
obj.className[1]=obj.className[1]

db.properties

db.username=admin
db.password=admin123456
mail.port=2555

访问 http://localhost:8080/task/test/

result:=myName:application-duan
port:2555
dbUserName:admin
objectProperties:ObjectProperties [name=obj.name, age=obj.age, className=[obj.className[0], obj.className[1]]]
关于作者

我是小小,一枚生于二线活在一线城市的程序猿,我是小小,我们下期再见。

 

 

惊呆了! | Spring Boot 使用 @Value 读取配置还能这样用_Spring Boot