SpringBoot配置文件与生产环境和开发环境配置

    |     2017年6月16日   |   springboot   |     0 条评论   |    5715

一、SpringBoot生产环境和开发环境配置

1.定义生产环境配置文件为 application-product.yml

server:
  port: 8081
spring:  
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/productDb
    username: root
    password: 123456  

2.定义开发环境配置文件为 application-dev.yml

server:
  port: 8080
spring:  
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/devlepmentDb
    username: root
    password: kf123  

3.配置文件application.yml中设置当前环境

spring:
  profiles:
    active: dev

二、SpringBoot获取配置文件数据有两种方式

首先在配置文件application.yml中准备好数据

test:
  username: viktor
  password: 123

获取方式一:通过@Value注解获取

缺点:需要在每个元素上添加注解

@Controller
@RequestMapping("/config")
public class ConfigeController {
	@Value(value="${test.username}")
	private String userName;

	@Value(value="${test.password}")
	private String passWord;

	@RequestMapping("")
	@ResponseBody
	public String config() {
		return "config == "+userName+" "+passWord;
	}

}

获取方式二: 通过@ConfigurationProperties注解获取

1.在类上添加注解@ConfigurationProperties(prefix=”test”); prefix=”test”为获取元素前缀,如:test.username
2.类中属性名与配置中元素名相同
3.添加geter,seter方法
4.也是重点,添加@ConfigurationProperties注解依赖
<!-- 支持 @ConfigurationProperties 注解 yml配置文件-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>

5.ConfigeControllerNew.java

@Controller
@RequestMapping("/confignew")
@ConfigurationProperties(prefix="test")
public class ConfigeControllerNew {
	private String username;
	private String password;

	@RequestMapping("")
	@ResponseBody
	public String config() {
		return "config == "+username+" "+password;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

实际应用

1. 配置文件application.yml包含如下信息

user
  username: 张三
  age: 23

2. 定义获取配置文件属性的工具类

@Component
@ConfigurationProperties(prefix = "user")
public class UserProperties {

    private String username;

    private Integer age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username= username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

3. 在Controller类或其它中使用

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private UserProperties userProperties;

    @GetMapping(value = "/proper")
    public String say() {
        return userProperties.getUsername();
    }
}
转载请注明来源:SpringBoot配置文件与生产环境和开发环境配置
回复 取消