application文件基本配置
默认为application.properties,但是我们一般建application.yml文件 application.yml文件可以进行树级书写配置,properties不可以,则会显得麻烦累赘。
properties 文件 server.port=8081 //配置8081端口,默认为8080端口 server.servlet.context-path=/springbootdemo //配置项目访问路径 yml文件 server: port: 8081 servlet: context-path: /springbootdemo注意:“:”冒号后必须跟空格再书写,这样文件才可以识别
多环境配置多yml文件的使用
建立application-dev.yml文件 ,此为本地使用的配置建立application-prod.yml文件,此为公司使用的配置application.yml文件,此为默认文件,通过此文件配置使用哪个文件,以及本地和公司公用部分配置。application.yml文件
#在这个配置文件中邪配置,则dev和prod都可以使用的到 spring: profiles: active: prod #active 配置使用哪个yml配置文件 #此时有两个配置文件 application-dev.yml 与 application-prod.yml #当写dev时,则使用application-dev.yml文件,当使用prod时,application-prod.yml自定义属性
application.properties提供自定义属性的支持,这样我们就可以把一些常量配置在这里
一个个属性单独配置:application.yml:我们定义cup和age,content属性和值
cup: B age: 18 content: "cup: ${cup}, age: ${age}" //在配置文件中读取配置文件属性值新建HelloCupConteoller
package com.demo.springbootdemo.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloCupController { //将配置文件的内容注入属性中 //在配置文件中,不需要指定类型,在需要注入的地方,指定属性类型即可 @Value("${cup}") private String cup; @Value("${age}") private Integer age; //在配置中使用配置属性 @Value("${content}") private String content; @RequestMapping(value="/helloval",method = RequestMethod.GET) public String say(){ return cup + age + content; } }若我们有多个属性,则需要在yml文件中配置多个,在controller中引入多个,太繁琐,此时我们可以使用类来封装这些属性。
使用类封装属性
1.新建GirlProperties.java,获得相应配置信息
package com.demo.springbootdemo.Properties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component // 获取前缀是girl的配置 @ConfigurationProperties(prefix = "girl") public class GirlProperties { private String cup; private Integer age; public String getCup() { return cup; } public void setCup(String cup) { this.cup = cup; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } 2.application.yml,直接使用实体类,属性 girl: cup: B age: 18 3.HelloCupController中,用GirlProperties获得配置值 package com.demo.springbootdemo.controller; import com.demo.springbootdemo.Properties.GirlProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloCupController { @Autowired private GirlProperties girlProperties; @RequestMapping(value="/hellopro",method = RequestMethod.GET) public String saypro(){ return girlProperties.getCup()+girlProperties.getAge(); } }