在我们的实际开发中,一般都有三套环境,开发环境,测试环境,生产环境,三套环境的数据库连接配置也有所不同,比如,端口,IP地址等等。如果在打包时候都频繁的修改配置文件信息,那必将是非常容易出错的地方。
在springBoot多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识.
application-dev.properties
com.name=this is dev
com.gender=man
application-test.properties
com.name=this is test
com.gender=man
application-pro.properties
com.name=this is pro
com.gender=man
新建一个类来获取配置文件中的值
package com.hf.moredev.model;
import lombok.Data;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Description:
* @Date: 2019/2/14
* @Auther:
*/
@Component
@Data
@ToString
public class User {
@Value("${com.name}")
private String name;
@Value("${com.gender}")
private String gender;
}
测试:
package com.hf.moredev.controller;
import com.hf.moredev.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Date: 2019/2/14
* @Auther:
*/
@RestController
public class TestController {
@Autowired
private User user;
@GetMapping("/user")
public String test(){
System.out.println(user.getName());
return user.toString();
}
}