springboot一、读取.yml或.properties数据

一、注入信息的两种方式

方式一:application.yml

#book info
book: 
  name: "《安娜卡列尼娜》"
  auther: "列夫托尔斯泰"
#people info
person:  
  name: "david"
  age: "22"
  sex: "男"
  phone: "16604578552"

方式二:application.properties

book.name="\u6218\u4E89\u4E0E\u548C\u5E73"
boot.auther="\u5B89\u5A1C\u5361\u5217\u5C3C\u5A1C"

person.name="david"
person.sex="\u7537"
person.age="22"
person.phone="16644525432"

二、编写配置类

方式一:

package com.zed.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class BookProperties {
	@Value("${book.name}")
	private String bookName;
	@Value("${book.auther}")
	private String auther;

	public String getBookName() {return bookName;}
	public void setBookName(String bookName) {this.bookName = bookName;}
	public String getAuther() {return auther;}
	public void setAuther(String auther) {this.auther = auther;}
}

方式二:

package com.zed.config;

import javax.validation.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

@Component
@ConfigurationProperties(prefix="person")
@Validated

public class PersonComponent {
	@NotEmpty
	private String name;
	@NotEmpty
	private String age;
	@NotEmpty
	private String sex;
	@NotEmpty
	private String phone;
	
	public String getName() {return name;}
	public void setName(String name) {this.name = name;}
	public String getAge() {return age;}
	public void setAge(String age) {this.age = age;}
	public String getSex() {return sex;}
	public void setSex(String sex) {this.sex = sex;}
	public String getPhone() {return phone;}
	public void setPhone(String phone) {this.phone = phone;}	
}

三、编写Controller类

@RestController
public class ShowController {
	@Autowired
	private BookProperties bookProperties;
	@Autowired
	private PersonComponent personComponent;
	
	@GetMapping("/book")
	public String show() {return "the book name is:"+bookProperties.getBookName()+"the auther is:"+bookProperties.getAuther();}
	@GetMapping("/user")
	public String user() {return "the name is:"+personComponent.getName()+"the age is:"+personComponent.getAge()+"the sex is:"+personComponent.getSex()+"the phone is:"+personComponent.getPhone();}
}

猜你喜欢

转载自blog.csdn.net/davidbieber/article/details/83060489