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