一、项目说明
项目环境:jdk1.8+tomcat8+idea2018
源代码github地址:
实现目标:springBoot中对于项目的依赖,插件等都采用了自动化配置,但是在实际生产中难免会手动配置一些内容。在使用spring构建项目时一般使用.xml/.properties文件保存配置,在springBoot构建的项目中也可以使用.properties作为配置文件或者使用.yaml。这里通过.properties的方式作为配置文件,了解其基本的配置与使用。
二、配置说明
(1)配置文件存放的位置
注:配置文件可以放在如下四个位置,四个位置的加载顺序与标注的序号一致。
(2)idea中修改.properties文件编码
说明:选中当前项目->File->Settings...->File Encodings
(3)配置文件映射到实体类
(4)代码说明
A:application.properties配置文件,这里user的几种属性名称的写法实体类都能识别
user.user_name = 张三
user.userAge = 18
user.user-address = 中国
user.USERSEX = 男
B:User映射实体类
@Component:实体类注解
@ConfigurationProperties(prefix = "user"):配置从properties文件中读取以user为前缀的数据
package com.example.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "user")
public class User {
private String userName;
private Integer userAge;
private String userAddress;
private String userSex;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public User(String userName, Integer userAge, String userAddress, String userSex) {
this.userName = userName;
this.userAge = userAge;
this.userAddress = userAddress;
this.userSex = userSex;
}
public User() {
}
}
C:HelloSpringbootController
package com.example.controller;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloSpringbootController {
@Autowired
User user;
@GetMapping("/springBoot")
public String sayHello(){
return "Hello Springboot!";
}
@GetMapping("/getUser")
public String getUser(){
return user.getUserName() + user.getUserSex() + user.getUserAge() + user.getUserAddress();
}
}
(4)启动项目,并访问