为了更好的使用springboot,所以看一下application.yml配置这块。主要是看数据绑定这块。
主要参考:https://www.hangge.com/blog/cache/detail_2459.html
package com.shuimutong.learn.springboot.yml.controller; import com.alibaba.fastjson.JSON;import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class HelloController { @GetMapping("/hello2") public String hello2() { return "Hello, Jack!"; } }
package com.shuimutong.learn.springboot.yml; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class YmlApplication { public static void main(String[] args) { SpringApplication.run(YmlApplication.class, args); } }
在resources目录下新建application.yml,并写入以下内容,
server: port: 8081
启动服务,从日志看出端口变更为8081,访问url说明配置生效。
my: name: Big大 age: 20 info: name:${my.name}--age:${my.age}
package com.shuimutong.learn.springboot.yml.bean; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component @Data public class MyData { @Value("${my.name}") private String name; @Value("${my.age}") private int age; @Value("${my.info}") private String info; }
使用@Value注解绑定application.yml中的配置
@Resource private MyData myData; @GetMapping("/getData") public MyData getMyData() { return myData; }
{"name":"Big大","age":20,"info":"name:Big大--age:20"}
说明值绑定正常。
classroom: clazz: 一年级 grade: 3班 seatNum: 30 courses: - 语文 - 数学 - 英语 - 化学 - 体育 - 美术 students: - name: 张三 age: 8 - name: 李四 age: 9
//Classroom类 package com.shuimutong.learn.springboot.yml.bean; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; @Data @Component @ConfigurationProperties(prefix = "classroom") public class Classroom { private String clazz; private String grade; private int seatNum; private List<String> courses; private List<Student> students; } //Student类 package com.shuimutong.learn.springboot.yml.bean; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data public class Student { private String name; private int age; }
@Resource private Classroom classroom; @GetMapping("/classInfo") public Classroom getClassroomInfo() { System.out.println("this is stu:" + JSON.toJSONString(student)); return classroom; }
{"clazz":"一年级","grade":"3班","seatNum":30,"courses":["语文","数学","英语","化学","体育","美术"],"students":[{"name":"张三","age":8},{"name":"李四","age":9}]}
符合预期。
可以的!
将内容从application.yml中抽出来。
增加以下内容:
spring: profiles: active: - classroom
配置那块你没看错,yml文件名一定要以“application-”开头。
3)启动程序验证
有,请移步git: https://github.com/shuimutong/spring_learn/tree/master/spring_boot/yml