springboot(二):springboot的配置文件application.properties与appliction.yml

前言:在springboot中.properties与.yml是两种不同格式的配置文件,

        .properties是xxx.xxx.xxx=xxx的格式,

        .yml则展示出了层次感。

一:application.properties
1.自定义配置
在application.properties中自定义参数和值并获取:

a.自定义参数:

#用户名
account=robert
#密码
password=123456

b.写个配置类

package com.robert.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * 配置类
 * @author L
 */
@Component
public class Properties {
    /**
      * 用户名
      */
    @Value("${account}")
    private String account;
    /**
     * 密码
     */
    @Value("${password}")
    private String password;
    //get、set省略
}

c.写个controller用来测试获取到的配置:

@Controller
public class testController {
	 @Autowired
	 Properties properties;
	 
     @RequestMapping("/getUser")
     public String test(ModelMap model) {
    	 String name = properties.getAccount();
    	 String password = properties.getPassword();
    	 return name+","+password;
     }
    
}

d.在浏览器地址栏输入:localhost:8080/getUser

结果是:用户名:robert 密码:123456

注意:配置文件中还有很多默认的参数,比如说这里的用户名,如果你用username,出来的是你电脑用户账号,所以在选择自定义名称时需要注意。

2.在正式的项目中,我们可能会有测试环境、生产环境,这时候我们需要把这些环境的配置分开。这时候,只需要配置多个配置文件即可。格式:application-{profile}.properties

例如:application-dev.properties、application-produce.properties

激活哪个配置文件:

spring.profiles.active=dev(或者produce)

二、application.yml

.yml格式如下,.properties中server.port=xxxx,到了.yml中就变成了

server:

     port:(空格)9090

注意空格,这是.yml的格式,不可缺少。

猜你喜欢

转载自blog.csdn.net/qq_27935743/article/details/80899226
今日推荐