在src/main/resources下添加配置文件application.properties 例如修改端口号
#端口号server.port=8089在src/main/resources下添加,application-pro.properties,application-dev.properties和application.properties三个文件 application.propertie
spring.profiles.active=devapplication-pro.properties
#端口号server.port=80#自定义端口号读取my.name=pzr.devapplication-dev.properties
#端口号server.port=8089#自定义端口号读取my.name=pzr.pro当application.propertie设置spring.profiles.active=dev时,则说明是指定使用application-dev.properties文件进行配置
TestController.java
package com.gyqc.ms.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.gyqc.ms.entity.config.ObjectProperties;/** * 测试接口 * @author pzr * */@Controller@RequestMapping("/testController")@PropertySource({"classpath:config/my.properties","classpath:config/config.properties"})public class TestController { //在application.properties中的文件,直接使用@Value读取即可,applicarion的读取优先级最高 @Value("${my.name}") private String myName; //如果多个文件有重复的名称的属性话,最后一个文件中的属性生效 @Value("${my.name1}") private String myName1; @Value("${my.name2}") private String myName2; @Autowired ObjectProperties objectProperties; @RequestMapping("/test") @ResponseBody String test() { return "myName:"+myName+" myName1:"+myName1+" name:"+myName2; } /** * 使用对象映射的方式读取配置文件 * @return */ @RequestMapping("/test1") @ResponseBody String test1(){ StringBuffer sb = new StringBuffer(); sb.append(" name:"); sb.append(objectProperties.getName()); sb.append(" age:"); sb.append(objectProperties.getAge()); sb.append(" className:"); for(String str : objectProperties.getClassName()){ sb.append(str); sb.append(","); } return sb.toString(); }}ObjectProperties.java
package com.gyqc.ms.entity.config;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 pzr * */@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; }}object.properties
#自定义属性读取obj.name=obj.nameobj.age=obj.ageobj.className[0]=obj.className[0]obj.className[1]=obj.className[1]新闻热点
疑难解答