springboot读取application.yaml文件数据
前言
提示:这里可以添加本文要记录的大概内容:
提示:以下是本篇文章正文内容,下面案例可供参考
一、创建并编辑对应的文件
1.application.yaml
!!!这里一定要注意,datasource一定不能写成dataSource,因为会和Spring内部的产生冲突
server:
port: 8080
contry: china
user:
- name: zhangsan
age: 18
- name: lisi
age: 20
likes:
- ball
- code
- game
baseDir: c:/win10
tempDir: ${baseDir}/temp
datasource:
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/springboot_db
username: root
password: root
2.MyDataSource
package com.codejams;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="datasource")
public class MyDataSource {
private String driver;
private String url;
private String username;
private String password;
@Override
public String toString() {
return "MyDataSource{" +
"driver='" + driver + '\'' +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
二、使用步骤
1.测试代码
代码如下(示例):
package com.codejams.controller;
import com.codejams.MyDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("books")
public class BookController {
@Value("${contry}")
private String contry;
@Value("${user[1].name}")
private String name;
@Value("${likes[1]}")
private String like;
@Value("${tempDir}")
private String tempDir;
@Autowired
private Environment env;
@Autowired
private MyDataSource myDataSource;
@GetMapping
public String test(){
System.out.println("running...");
System.out.println(contry);
System.out.println(name);
System.out.println(like);
System.out.println(tempDir);
System.out.println("----------------------------");
System.out.println(env.getProperty("contry"));
System.out.println(env.getProperty("user[1].name"));
System.out.println("----------------------------");
System.out.println(myDataSource);
return "running..";
}
}
2.效果展示
如下(示例):
|