Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 视频教程 | 打赏(Donations) | About
知乎专栏多维度架构

5.6. Properties 文件

5.6.1. @Value 注解

application.properties

			
server.name=Linux
server.host=192.168.0.1,172.16.0.1			
			
		
			
	@Value("${server.name}")
	private String name;
 			
		

处理逗号分割得值

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

默认值

			
@Value("${server.name:Windows}") 如果application.properties没有配置server.name那么默认值将是 Windows
private String name;
				
@Value("${some.key:my default value}")
private String stringWithDefaultValue;
			
@Value("${some.key:true}")
private boolean booleanWithDefaultValue;

@Value("${some.key:42}")
private int intWithDefaultValue;			

@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
 
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;

// Using SpEL
@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;
			
		

Null 默认值

			
	@Value("${app.name:@null}") // app.name = null
 	private String name;			
			
		

5.6.2. containsProperty 读取配置文件

		
this.environment.containsProperty("spring.jpa.database-platform")		
		
		

5.6.3. @PropertySource 注解载入 properties 文件

			
@PropertySource("classpath:/config.properties}")	

忽略FileNotFoundException,当配置文件不存在系统抛出FileNotFoundException并终止程序运行,ignoreResourceNotFound=true 会跳过使程序能够正常运行
@PropertySource(value="classpath:config.properties", ignoreResourceNotFound=true)		

			
		

载入多个配置文件

			
@PropertySources({  
        @PropertySource("classpath:config.properties"),  
        @PropertySource("classpath:db.properties")  
})
			
		

test.properties

			
name=Neo
age=30			
			
		
			
package cn.netkiller.web;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@PropertySource("classpath:test.properties")
public class TestController {
	
	@Autowired
	Environment environment;
	
	@Value("${age}")
	private String age;

	public TestController() {
		// TODO Auto-generated constructor stub
	}
	
	// 环境变量方式
	@RequestMapping("/test/env")
	@ResponseBody
	public String env() {
		String message = environment.getProperty("name");
		return message;
	}
	
	@RequestMapping("/test/age")
	@ResponseBody
	public String age() {
		String message = age;
		return message;
	}

}
			
		

5.6.4. @EnableConfigurationProperties 引用自定义 *.properties 配置文件

Application.java 涮锅配置NetkillerProperties.java是 @ComponentScan 扫描范围,可以不用声明下面注解。

			
@EnableConfigurationProperties(NetkillerProperties.class)	
			
		
			
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;

import pojo.NetkillerProperties;

@Configuration
@SpringBootApplication
@EnableConfigurationProperties(NetkillerProperties.class)
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
@ComponentScan({ "web", "rest" })
@EnableMongoRepositories
public class Application {
	
	@SuppressWarnings("deprecation")
	public @Bean MongoDbFactory mongoDbFactory() throws Exception {
		UserCredentials userCredentials = new UserCredentials("finance", "your_password");
		return new SimpleMongoDbFactory(new Mongo("mdb.netkiller.cn"), "finance", userCredentials);
	}

	public @Bean MongoTemplate mongoTemplate() throws Exception {
		return new MongoTemplate(mongoDbFactory());
	}

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}
			
		

NetkillerProperties.java

			
package pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix="netkiller")
public class NetkillerProperties {
	private String name;
	private String email;
	private String home;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getHome() {
		return home;
	}
	public void setHome(String home) {
		this.home = home;
	}
	@Override
	public String toString() {
		return "NetkillerProperties [name=" + name + ", email=" + email + ", home=" + home + "]";
	}
}
			
		

IndexController.java

			
package web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import domain.City;
import pojo.NetkillerProperties;
import repository.CityRepository;

@Controller
public class IndexController {
	
	@Autowired
	private CityRepository repository;

	@Autowired
	private NetkillerProperties propertie;
	
	@RequestMapping("/index")
	@ResponseBody
	public String index() {
	//public ModelAndView index() {

		String message = "Hello";
		//return new ModelAndView("home/welcome", "variable", message);
		return message;
	}
	
	@RequestMapping("/config")
	@ResponseBody
	public String config() {
		return propertie.toString();
	}
}
			
		

src/main/resource/application.properties

			
netkiller.name=Neo
netkiller.email=netkiller@msn.com
netkiller.home=http://www.netkiller.cn
			
		

@ConfigurationProperties 默认配置是 application.properties

你可以通过 locations 指向特定配置文件

			@ConfigurationProperties(prefix = "message.api",locations = "classpath:config/message.properties")
		

@EnableConfigurationProperties 可以导入多个配置文件

			@EnableConfigurationProperties({NetkillerProperties.class, NeoProperties.class})
		

5.6.5. 手工载入 *.properties 文件

			
	@RequestMapping("/config")
	@ResponseBody
	public void config() {
		try {
			Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("/config.properties"));
			for(String key : properties.stringPropertyNames()) {
				  String value = properties.getProperty(key);
				  System.out.println(key + " => " + value);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
			
		

5.6.6. spring.profiles.active 参数切换配置文件

首先我们准备三个配置文件

			
src/main/resource/application-development.properties
src/main/resource/application-testing.properties
src/main/resource/application-production.properties			
			
		

使用下面--spring.profiles.active参数切换运行环境配置文件

			
java -jar application.jar --spring.profiles.active=development
java -jar application.jar --spring.profiles.active=testing
java -jar application.jar --spring.profiles.active=production			
			
		

分别为三个环境打包

			
mvn clean package -Pdevelopment
mvn clean package -Ptesting
mvn clean package -Pproduction			
			
		

5.6.7. SpringApplicationBuilder.properties() 方法添加配置项

		
			
  public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class).properties("spring.config.name=client").run(args);
  }			
			
		

5.6.8. 参数引用

		
book.name=SpringCloud
book.author=netkiller
book.title=《${book.name}》作者 ${book.author}
		
		

5.6.9. 产生随机数

		
# 随机字符串
cn.netkiller.blog.value=${random.value}
# 随机整数
cn.netkiller.blog.number=${random.int}
# 随机长整数
cn.netkiller.blog.bignumber=${random.long}
# 随机10以内的数
cn.netkiller.blog.1=${random.int(10)}
# 随机10-20之间的数值
cn.netkiller.blog.2=${random.int[10,20]}		
		
		

5.6.10. List 列表类型

List类型在properties文件中使用[]来定义列表类型,比如:

		
sms.url[0]=http://api1.example.com
sms.url[1]=http://api2.example.com

netkiller.book[0].title=Netkiller Linux 手札
netkiller.book[0].author=netkiller

netkiller.book[1].title=Netkiller Spring 手札
netkiller.book[1].author=netkiller
		
		

注意:在Spring Boot 2.0中对于List类型数组下标的配置必须是连续的,否则会抛出UnboundConfigurationPropertiesException异常,所以如下配置是不允许的:

		
foo[0]=a
foo[2]=b		
		
		

使用逗号分割的配置方式,上面与下面的配置是等价的:

		
sms.url[0]=http://api1.example.com,http://api2.example.com		
		
		

在yaml文件中使用可以使用如下配置:

		
email:
  to:
    address:
      - neo@netkiller.cn
      - jam@netkiller.cn
		
		

逗号分割的方式:

		
email:
  to:
    address: neo@netkiller.cn, jam@netkiller.cn
		
		

命令行传递 List 数据

		
java -jar -D"api.url[0]=http://api1.example.com" \
	-D"api.url[1]=http://api2.example.com" \
	api.netkiller.cn-v1.0.jar
	
逗号分割的方式,比如:

java -jar -Dapi.url=http://api1.example.com,http://api2.example.com demo.jar	
		
		

5.6.11. Map类型

Map类型在properties和yaml中的标准配置方式如下:

		
properties格式:		
netkiller.key=value

yaml格式:
netkiller:
  key: value
  
举例:
user:
  name: neo
  gender: male
  age: 30
		
		

注意:如果Map类型的key包含字母数字和-以外的字符,需要用[]括起来,比如:

		
user:
  name:
    '[first.name]': neo
    '[last#name]': chen
		
		

5.6.12. Binder

		
cn.netkiller.author=bar
cn.netkiller.journal[0]=Spring Boot
cn.netkiller.journal[1]=Spring Cloud

cn.netkiller.books[0].title=Netkiller Spring Boot 手札
cn.netkiller.books[0].url=http://www.netkiller.cn/spring/
cn.netkiller.books[1].title=Netkiller Java 手札
cn.netkiller.books[1].url=http://www.netkiller.cn/linux/		
		
		
		
@Data
@ConfigurationProperties(prefix = "cn.netkiller")
public class NetkillerProperties {

    public String author;

}		
		
		
		
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Application.class, args);

        Binder binder = Binder.get(context.getEnvironment());
        NetkillerProperties prop = binder.bind("cn.netkiller", Bindable.of(NetkillerProperties.class)).get();
        System.out.println(prop.author);
        
		List<String> journal = binder.bind("cn.netkiller.journal", Bindable.listOf(String.class)).get();
		System.out.println(journal);
		
		List<Book> books = binder.bind("cn.netkiller.book", Bindable.listOf(Book.class)).get();
		System.out.println(books);

    }
}