项目目录
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wo</groupId>
<artifactId>springboot-first</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-first</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<!--web工程-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--启动热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.TestTwoController
@RestController
@RequestMapping("/two")
public class TestTwoController {
// @Value("${class.name}")
// public String name;
@Value(("${class.student.name}"))
public String userName;
@Value(("${class.student.age}"))
public String age;
@Value(("${class.student.sex}"))
public String sex;
@Autowired
public Student student;
@RequestMapping("/first")
public String first(){
return "hello"+student;
}
}
3.application.yml;
server:
port: 8089
class:
student:
name: 王
age: 18
sex: 男
teacher:
name: 教师
age: 18
sex: 女
4.application.properties
#server.port=8088
#class.name=2004
配置文件先执行yml,最后执行properties,如果配置相同,后置覆盖前者。
5.实体类
@ConfigurationProperties(prefix = "class.student")
@Component
public class Student {
private String name;
private Integer age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
6.测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootFirstApplicationTests {
@Autowired
TestController testController;
@Test
public void contextLoads() {
String first = testController.first();
System.out.println(first);
}
}