一、自定义属性
创建工程的时候系统默认会在src/main/java/resources目录下创建一个application.properties,结合教程和现在的项目,改为改为application.yml
二、将配置文件的属性赋给实体类
创建一个实体:
配置文件,其中配置文件中用到了${random} ,它可以用来生成各种不同类型的随机值。
controller,可加个注解@ConfigurationProperties,也可以不加,spring现在版本会默认帮你办到。
package com.dennis.demo.controller;
import com.dennis.demo.entity.User;
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.RestController;
/**
* @author Dennis
* @date 2020/1/8
*/
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
User user;
@Value("${my.name}")
private String name;
@Value("${my.age}")
private int age;
@RequestMapping("/dennis")
public String hello() {
return "hello,Dennis";
}
@RequestMapping("/get")
public String getNameAndAge() {
return name + " " + age;
}
@RequestMapping("/user")
public String getuser() {
return user.getName() + " " + user.getAge() + " " + user.getBodySize() + " " + user.getUuid() + " " + user.getMax() + " " + user.getGreeting();
}
}
三、自定义配置文件
有时候不一定把配置都写到application.yml中。自定义配置文件,如test.properties:
实体类:
controller:
四、多个环境配置文件
现实的开发环境中,我们需要不同的配置环境,比如:
application-test.properties:测试环境
application-dev.properties:开发环境
application-prod.properties:生产环境
yml文件格式也是一样,如图:
如下图不同环境不同配置: