一、在resources下面创建test.properties文件
内容如下:
com.test.name=zhangys
com.test.age=20
二、创建User
package com.hundsun.springcloud.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* @Description:
* @author:zhangys
* @date:Created in 13:14 2019/6/5
* @Modified By:
*/
@Configuration
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.test")
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
三、创建ResourceController
package com.hundsun.springcloud.resources;
import com.hundsun.springcloud.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @author:zhangys
* @date:Created in 10:53 2019/6/5
* @Modified By:
*/
@RestController
@RequestMapping("/resource")
public class ResourceController {
@Autowired
private User user;
@RequestMapping(value = "/getTestProperties")
public String getTestProperties(){
return user.toString();
}
}
四、测试如下:
浏览器输入:http://localhost:8080/resource/getTestProperties
五、多个环境的配置文件
Spring Boot 支持程序启动时在配置文件applicaition.yml 中指定环境的配置文件。
application-test.properties——测试环境
application-dev.properties——开发环境
application-prod.properties——生产环境
在application.yml 中加上spring.profiles.active 的配置,该配置指定采用哪一个profiles
spring :
profiles :
active: dev
通过 java -jar 这种方式启动程序,并指定程序的配置文件,启动命令如下:
java -jar springbootdemo jar -- spring profiles active=dev