3.5. Properties

简介:

3.5.1. 载入*.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();
		}
	}	
			
			

3.5.2. @Value 注解

application.properties

server.name=Linux
server.host=192.168.0.1,172.16.0.1
			
			
	@Value("${server.name}")
	private String name;
	
	@Value("${server.name:Windows}") 如果application.properties没有配置server.name那么默认值将是 Windows
	private String name;
	
	@Value("${app.name:@null}") // app.name = null
 	private String name;
 	
 	@Value("#{'${server.host}'.split(',')}") 
 	private List<String> host;
 			
			

3.5.3. @PropertySource 注解

			
@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;
	}

}
			
			



原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

目录
相关文章
|
XML 存储 安全
一文带你全面了解Properties类
一文带你全面了解Properties类
122 0
一文带你全面了解Properties类
|
Java Spring
application.properties或.yml文件
application.properties或.yml文件
92 0
application.properties或.yml文件
|
XML 移动开发 Java
详解log4j.properties配置
详解log4j.properties配置
|
机器学习/深度学习 关系型数据库 Oracle
xtt.properties
Reduce Transportable Tablespace Downtime using Incremental Backups (Doc ID 1389592.1) Properties file for xttdriver.
942 0
|
Java Spring
|
Windows Linux
|
Java 网络架构
|
NoSQL Java 网络安全
|
NoSQL Java 网络安全