SpringBoot(二)SpringBoot多环境配置

Spring框架常用注解简单介绍
SpringMVC常用注解简单介绍
SpringBoot(一)创建一个简单的SpringBoot工程
SpringBoot(二)SpringBoot多环境配置
SpringBoot(三)SpringBoot整合MyBatis
SpringBoot(四)SpringBoot整合 Redis

SpringBoot配置文件介绍

SpringBoot的配置文件用于配置SpringBoot程序,有两种格式的配置文件:

  1. .properties文件
  2. .yml文件
创建application.properties配置文件
.properties配置文件
# 设置端口号
server.port=8080
# 设置服务名称
spring.application.name=service-product

# 设置上下文,设置后访问服务时需要在url前面拼上设置的内容,这里一般设置为服务名称
spring.server.context-path=/springbootdemo
server.servlet.context-path=/springbootdemo

启动工程,然后打开浏览器输入:http://localhost:8080/springbootdemo/product/12

SpringBoot多环境配置

我们可以指定SpringBoot的激活配置文件。如果主配置文件中指定了激活的配置文件,那么即使在主配置文件中指定了配置信息,还是优先使用激活文件中的配置信息,如果激活文件中没有,就去主配置文件中去查找。

我们先创建多个环境的配置文件
配置文件
  1. application-dev.properties
server.port=8081
spring.application.name=service-product

spring.server.context-path=/springbootdemo
server.servlet.context-path=/springbootdemo
  1. application-test.properties
server.port=8082
spring.application.name=service-product

spring.server.context-path=/springbootdemo
server.servlet.context-path=/springbootdemo
  1. application-pro.properties
server.port=8088
spring.application.name=service-product

spring.server.context-path=/springbootdemo
server.servlet.context-path=/springbootdemo
  1. 修改application.properties,指定激活的配置文件
## 设置端口号
#server.port=8080
## 设置服务名称
#spring.application.name=service-product
#
## 设置上下文,设置后访问服务时需要在url前面拼上设置的内容,这里一般设置为服务名称
#spring.server.context-path=/springbootdemo
#server.servlet.context-path=/springbootdemo

#指定激活的配置文件
spring.profiles.active=dev

打开浏览器输入:http://localhost:8081/springbootdemo/product/12(此时访问的是dev环境,端口变成了8081)

SpringBoot自定义配置

我们可以再SpringBoot配置文件中添加一些自定义配置,然后通过@Value读取配置的属性值。

## 设置端口号
#server.port=8080
## 设置服务名称
#spring.application.name=service-product
#
## 设置上下文,设置后访问服务时需要在url前面拼上设置的内容,这里一般设置为服务名称
#spring.server.context-path=/springbootdemo
#server.servlet.context-path=/springbootdemo

#指定激活的配置文件
spring.profiles.active=dev

#自定义配置
product.name=SpringBootDemo

使用@Value在Dao中读取自定义配置的属性值

@Repository
public class ProductDao {

    @Value("${product.name}")
    private String name;

    public Product getProductById(String id) {
        Product product = new Product();
        product.setId(id);
        product.setName(name);
        product.setPrice(13.6);
        return product;
    }

}

启动工程,然后打开浏览器输入:http://localhost:8081/springbootdemo/product/12
接口返回:

{
"id": "12",
"name": "SpringBootDemo",
"price": 13.6
}
最后编辑于:2020-08-19 16:27


喜欢的朋友记得点赞、收藏、关注哦!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武昌库里写JAVA

您的鼓励将是我前进的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值