src/main/resources 下
spring boot 2.0后配置:
server.port=8081
server.servlet.context-path=/girl
视频内配置:
server.port=8081
server.context-path=/girl
yml文件配置是廖师兄推荐模式,从视频中也发现yml的配置要比properties配置简单、直观。
2.0版本配置:
server:
port: 8082
servlet:
context-path: /girltest
视频版本配置:
server:
port: 8082
context-path: /girltest
注意:这里的语法在冒号后面有一个空格,idea中不写空格,前面的属性颜色就显示为黑色,正常为蓝色。
配置文件编写:
server:
port: 8080
cupSize: B
代码编写
@RestController
public class HelloController {
@Value("${cupSize}")
private String cupSize;
@RequestMapping( value = "/hello",method = RequestMethod.GET)
public String say(){
return cupSize;
}
}
查看结果
配置属性:
server:
port: 8080
cupSize: B
age: 18
代码编写:
@RestController
public class HelloController {
@Value("${cupSize}")
private String cupSize;
@Value("${age}")
private Integer age;
@RequestMapping( value = "/hello",method = RequestMethod.GET)
public String say(){
return cupSize + age;
}
}
说明:配置文件中值的属性由声明变量的位置决定
查看结果:
配置属性:
server:
port: 8080
cupSize: B
age: 18
content: "cupSize: ${cupSize}, age: ${age}"
代码编写:
@RestController
public class HelloController {
@Value("${cupSize}")
private String cupSize;
@Value("${age}")
private Integer age;
@Value("${content}")
private String content;
@RequestMapping( value = "/hello",method = RequestMethod.GET)
public String say(){
return content;
}
}
查看结果:
从3.3中发现,我们每一个配置都需要用@Value注解引入一次,这样会很麻烦,下面采用另外一种方式时间引入配置。
这里还是用到注解:@Autowired 用于注入,@Component 用于配合autowired使用。
server:
port: 8080
girl:
cupSize: B
age: 18
GirlProperties 代码:
package com.imooc;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String cupSize;
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
private Integer age;
}
controller代码:
@RestController
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping( value = "/hello",method = RequestMethod.GET)
public String say(){
return girlProperties.getCupSize();
}
}
视频中引入此内容的方式太羞羞了,这里就不描述了,目的就是在代码不变的情况下,程序在不同的环境下需要使用不同的配置,比较典型的就是开发环境和生产环境,我们不能在每次环境变化的时候都去修改一次配置文件,这样会增加很多不必要的工作量。
拷贝两份配置文件,分别增加标记为dev和prod
application-dev.yml配置:
server:
port: 8080
girl:
cupSize: B
age: 18
application-prod.yml配置:
server:
port: 8081
girl:
cupSize: F
age: 18
设置主配置文件为dev环境:
spring:
profiles:
active: dev
查看结果:
设置主配置文件为prod环境:
spring:
profiles:
active: prod
查看结果:
上诉方法依然需要通过更改配置文件来决定程序使用哪种环境,要想在不改变配置且需要在启动时使用自己想用的配置,可以使用上一章Spring Boot 学习(一)简介+第一个spring项目的2.5.2节 jar包启动方式来实现,示例:
mvn install
java -jar target/girl-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
若要使用dev环境,将“active=”后面的内容改为dev即可。
使用上面的命令,我们启动了prod环境,此环境的程序布置在8081端口上
然后我们在idea中使用dev环境启动,下面是两个端口并存的效果:
上一章:Spring Boot 学习(一)简介+第一个spring项目
下一章:Spring Boot 学习(三)Controller的使用