一、系统配置文件

1.application.properties是新建springboot项目后默认得配置文件

配置的示例如下

server.port=8080
server.context-path=/girl

2.推荐使用application.yml的方式

配置的示例如下

server:
  port: 8082
  context-path: /girl

二、YAML

YAML 语言教程

三、实际应用

1.@value 的用法

application.yml

server:
port: 8082
cupSize: B
age: 18
content: "cupSize: ${cupSize}, age: ${age}"

HelloController中对应的注入方式

@RestController
public class HelloController {

@Value("${cupSize}")
private String cupSize;

@Value("${age}")
private String age;

@Value("${content}")
private String content;

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say (){
return cupSize+","+age+";"+content;
}
}

浏览器输出为B,18;cupSize: B, age: 18

2.@component 和@ConfigurationProperties

 创建实体GirlProperties,其中(prefix="girl")代表适配 配置文件中所有girl开头的配置

package com.dechy.girl.girl;


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

@Component
@ConfigurationProperties(prefix="girl")
public class GirlProperties {
    private String cupSize;
    private Integer age;

    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;
    }
}

对应的controller代码为

package com.dechy.girl.girl;

import org.springframework.beans.factory.annotation.Autowired;
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 HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say (){
        return girlProperties.getCupSize();
    }
}

配置为

server:
  port: 8082
girl:
  cupSize: B
  age: 18

3.多环境使用不同的配置文件

将resources下的application.yml复制为application-dev.yml和application-prod.yml

内容分别如下

server:
  port: 8082
girl:
  cupSize: B
  age: 18
server:
  port: 8081
girl:
  cupSize: F
  age: 18

将application.yml修改为,代表我们使用dev这个配置

spring:
  profiles:
    active: dev

但是这样改使用仍然很麻烦,解决方法如下

使用如下方式启动

java -jar target/girl-0.0.1-SNAPSHOT.jar --spring.profile.active=dev

 

posted on 2017-11-07 16:26  knyel  阅读(255)  评论(0编辑  收藏  举报