一、使用@Value注解
一个@Value注解给一个属性赋值
package com.modi.hello.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Teacher {
// 通过@Value直接给属性赋值
@Value("3")
private int cid;
@Value("张老师")
private String nameTeacher;
public Teacher() {
}
public Teacher(int cid, String nameTeacher) {
this.cid = cid;
nameTeacher = nameTeacher;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getNameTeacher() {
return nameTeacher;
}
public void setNameTeacher(String nameTeacher) {
this.nameTeacher = nameTeacher;
}
@Override
public String toString() {
return "Teacher{" +
"cid=" + cid +
", nameTeacher='" + nameTeacher + '\'' +
'}';
}
}
二、通过application.yaml配置文件
在application.yaml配置文件中为属性赋值
在需要给属性赋值的类中使用@ConfigurationProperties注解为属性赋值。具体写法:
@ConfigurationProperties(prefix = “student”)
package com.modi.hello.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String name;
private int age;
private Teacher teacher;
private Map<String,Object> map;
private List<String> list;
private Date birthday;
public Student() {
}
public Student(String name, int age, com.modi.hello.pojo.Teacher teacher, Map<String, Object> map, List<String> list, Date birthday) {
this.name = name;
this.age = age;
this.teacher = teacher;
this.map = map;
this.list = list;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public com.modi.hello.pojo.Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher){
this.teacher = teacher;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", teacher=" + teacher +
", map=" + map +
", list=" + list +
", birthday=" + birthday +
'}';
}
}