Spring Boot 从入门到放弃:简单参数配置及环境分离

wshunli
2018-01-26 / 0 评论 / 83 阅读 / 正在检测是否收录...

本文记录下 Spring Boot 参数配置以及生产环境与开发环境分离配置。

推荐使用 yml 配置 Spring Boot ,可以省略重复内容,也有较好的提示。

直接修改 application.propertiesapplication.yml 即可。

简单参数配置

我们在使用 Spring Boot 时难免会使用一些简单的配置配置,
也就是在配置文件 application.yml 配置相应变量的值,然后使用 @Value 注解取得。

// application.yml
usename: wshunli
// HelloController
@Value(value = "${usename}")
String wshunli;

这样还是有点麻烦,我们可以新建一个类:

package com.wshunli.spring.boot.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "hello")
public class Hello {

    String name;
    String content;

    // 省略 get set 方法
}

这里可能提示添加依赖,我们根绝建议添加即可:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

在配置文件中这样写:

hello:
  name: hello prod
  content: Spring Boot !

在使用的地方:

@Autowired
Hello hello;

使用 get 方法即可得到所需的值。

环境分离

添加两个文件 application-dev.ymlapplication-prod.yml 分别代表开发环境和生产环境。

例如:

application-dev.yml

server:
  port: 8081

hello:
  name: hello dev
  content: Spring Boot !

application-prod.yml

server:
  port: 808

hello:
  name: hello prod
  content: Spring Boot !

在原来的配置文件中添加:

spring:
  profiles:
    active: dev

我们只需修改 active 的值即可在在环境之间切换,
dev 代表开发环境配置,prod 代表生产环境配置。

本文源码:https://github.com/wshunli/spring-boot-demo

0

评论 (0)

取消