Skip to main content

配置文件

[TOC]

初识

默认的 application.properties

server.port=8081
server.servlet.context-path=/girl

可以删除掉使用yml文件

创建 application.yml 文件

server:
port: 8082
servlet:
context-path: /girl

注解方式读取配置文件

server:
port: 8082
servlet:
context-path: /girl
cupSize: B
age: 18

页面代码

package cn.asdasd.demo;

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 {

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

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

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

}

配置文件用变量

cupSize: B
age: 18
content: "cupSize: ${cupSize},age: ${age} "

网页部分

package cn.asdasd.demo;

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 {

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

}

读取配置分组

girl:
cupSize: B
age: 18

创建一个类 GirlPropertie.java

package cn.asdasd.demo;

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

@Component
@ConfigurationProperties(prefix = "girl")
public class GirlPropertie {

private String cupSize;

private Integer age;


public String getCupSize() {
return cupSize;
}

public Integer getAge() {
return age;
}

public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}

public void setAge(Integer age) {
this.age = age;
}
}

网页代码

package cn.asdasd.demo;

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 GirlPropertie girlPropertie;

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

}

配置文件配置读取测试和生产环境

1. application.yml

spring:
profiles:
active: dev

2. 两个环境

application-dev.yml

server:
port: 8082
servlet:
context-path: /girl
girl:
cupSize: B
age: 18

application-prod.yml

server:
port: 8082
servlet:
context-path: /girl
girl:
cupSize: A
age: 16