3.5. Properties

本文介绍了Spring框架中如何通过不同方式加载配置文件,并实现属性注入。包括使用`PropertiesLoaderUtils`加载`.properties`文件,利用`@Value`注解读取配置值,以及使用`@PropertySource`指定配置文件源等技巧。
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 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值