springBoot项目属性配置

1、创建Spring Boot项目时,会默认生成一个全局配置文件application.properties(可以修改后缀为.yml),我们可以通过修改该配置文件来对一些默认配置的配置值进行修改。

1)修改tomcat启动端口,访问的根路径,

server:

  port: 8888

  servlet:

    context-path: /java001

2)自定义属性及读取

读取的时候通过Spring的@Value(“${属性名}”)注解即可。

eg:

1>、在application.yml定义几个常量:

buyer: 5

2>、Controller类读取自定义属性

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

 3)实体类属性赋值

当属性参数变多的时候,我们习惯创建一个实体,用实体来统一接收赋值这些属性。

1>、在application.yml定义变量组:

 application.yml配置girl

girl:
size: 3
length: 5
content: aaa

2>、创建实体类,需要在实体类上增加注解@ConfigurationProperties,并指定prrfix前缀。

 package com;


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

@ConfigurationProperties(prefix = "girl")
@Component
public class girl {
private String size;
private Integer length;
private String name;

public String getSize() {
return size;
}

public void setSize(String size) {
this.size = size;
}

public Integer getLength() {
return length;
}

public void setLength(Integer length) {
this.length = length;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

3>、编写Controller调用属性bean,EnableConfigurationProperties注解需要加在调用类上,或者加在启动类SpringbootSimpleApplication上也可以

 

package com;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class helloControllerr {
@Autowired
private girl girl;

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

}

 

4)多环境配置文件

使用多个yml配置文件进行配置属性文件

可以使用多个yml来配置属性,将于环境无关的属性放置到application.yml文件里面;通过与配置文件相同的命名规范,创建application-{profile}.yml文件 存放不同环境特有的配置,例如 application-test.yml 存放测试环境特有的配置属性,application-prod.yml 存放生产环境特有的配置属性。

通过这种形式来配置多个环境的属性文件,在application.yml文件里面spring.profiles.active=xxx来指定加载不同环境的配置,如果不指定,则默认只使用application.yml属性文件,不会加载其他的profiles的配置。

启动时可以看到:The following profiles are active: dev

 

 spring:

    profiles:

    -active: dev

5)自定义配置文件

注意:spring boot 1.5版本后@PropertySource注解就不能加载自定义的yml配置文件了

application.yml是系统默认的配置文件,当然我们也可以创建自定义配置文件,在路径src/main/resources下面创建文件test.properties

1>、test.properties配置文件配置

girl.size="88"

2>、创建实体类

@Component

@Configuration

@PropertySource("classpath:test.properties")

@ConfigurationProperties(prefix ="girl")

public class girl {

private Stringsize;

3>、Controller 读取配置

@RestController

@EnableConfigurationProperties({girl.class})

public class helloControllerr {

@Autowired

  private girlgirl;

@RequestMapping(value ="/hello", method = RequestMethod.GET)

public String say(){

return girl.getSize();

}

}

 

 
posted @ 2020-01-29 15:55  小马哥快快跑  阅读(135)  评论(0)    收藏  举报