springboot配置文件
springboot使用一个全局的配置文件,配置文件名称是固定的
- application.properties
语法结构 key=value
server.port=8090
- application.yml
语法结构 key:空格 value
springboot配置文件的作用:修改springboot自动配置的默认值,因为springboot在底层都给我们自动配置好了
YAML
Yet Another Markup Language
server:
port: 8080
#yml,对空格的要求十分严格!!!!.
#语法:普通属性/对象/数组
name : hhh
#对象
people:
sex: female
age: 3
people2: {sex: female, age: 3}
#数组
fruits:
- banana
- apple
fruits2: [banana, apple]
那么yml文件可以用来干啥呢,仔细看看我司的项目,发现在yml文件中几乎是一些配置。其实yml就是给属性赋值的。。。。举个栗子
其实在最开始看我司的项目的时候,还很好奇,这些yml中的值是怎么和对应的属性赋值的呢。像之前做node的时候,也是有很多的配置文件,但是那些配置文件显然都是通过解析json然后赋值的,这里的yml又是怎么赋值的呢?
带着这样的疑问,我发现了yml也太可了吧!!!!!!有多可,直接通过注解就能实现yml和属性的赋值。
yml属性赋值
正常的赋值-----spring bean正常通过注解实现依赖注入 @Component @Value
package com.example.springboot.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
public class People {
@Value("17")
private int age;
@Value("ddd")
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
使用yml赋值+@ConfigurationProperties @Component
package com.example.springboot.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "people")
public class People {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
application.yml
server:
port: 8080
people:
age: 12
name: dhy11
或者用@Value("${}")加上yml,@Component
package com.example.springboot.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
public class People {
@Value("${people.age}")
private int age;
@Value("${people.name}")
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
springboot多环境配置,
我的天哪,之前node的时候那环境配置,那个麻烦呀,不过也是原生,自己实现嘛,springboot直接就帮我们做了,厉害了
多环境配置实现如下
application,yml
spring: profiles: active: dev server: port: 8080
application-dev.yml
server: port: 8081
application-test.yml
server: port: 8082