springboot读取application.yaml文件数据
兴奋の大公猴 人气:0提示:以下是本篇文章正文内容,下面案例可供参考
一、创建并编辑对应的文件
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 #创建类:用于封装下面的数据 #由spring帮我们去加载数据对象中,一定告诉spring加载这组信息 #使用时候从spring中直接获取信息使用 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; //1.定义数据模型封装yaml文件中对应的数据 //2.定义为spring管控的bean @Component //3.指定加载的数据 @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 { //读取yaml文件 @Value("${contry}") private String contry; @Value("${user[1].name}") private String name; @Value("${likes[1]}") private String like; @Value("${tempDir}") private String tempDir; //使用Environment对象封装所有数据 @Autowired private Environment env; //查看datasource是否注入成功 @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.效果展示
如下(示例):
加载全部内容