在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在Springboot中获取配置文件的方式。
注:前三种测试配置文件为springboot默认的application.properties文件
一、@ConfigurationProperties方式
application.properties
com.xh.username=shercom.xh.password=123456
新建PropertiesConfig
@Component@ConfigurationProperties(prefix = "com.xh")//获取配置文件中以com.xh开头的属性public class PropertiesConfig { private String username; private String password; //get set 省略}
启动类PropertiesApplication
@SpringBootApplication@RestControllerpublic class PropertiesApplication { @Autowired PropertiesConfig propertiesConfig; public static void main(String[] args) { SpringApplication.run(PropertiesApplication.class, args); } @GetMapping("config") public String getProperties() { String username = propertiesConfig.getUsername(); String password = propertiesConfig.getPassword(); return username+"--"+password; }}
测试结果
二、使用@Value注解方式
启动类
@SpringBootApplication@RestControllerpublic class PropertiesApplication { @Value("${com.xh.username}") private String username; @Value("${com.xh.password}") private String password; @GetMapping("config") private String getProperties(){ return username+"---"+password; }
测试结果:
三、使用Environment
启动类
@SpringBootApplication@RestControllerpublic class PropertiesApplication { @Autowired Environment environment; @GetMapping("config") private String getProperties() { String username = environment.getProperty("com.xh.username"); String password = environment.getProperty("com.xh.password"); return username + "-" + password; }
测试结果: