4.通过application.yml读取:
/** * 学生实体类 * Created by ASUS on 2018/5/4 */ @Component("Student") public class Student { @Value("${student.name}") private String name; @Value("${student.age}") private int age; 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 Student(String name, int age) { this.name = name; this.age = age; } public Student() { } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
/** * springboot启动类 * */ @SpringBootApplication //读取resources目录下的application.yml @PropertySource("classpath:application.yml") public class Application { public static void main( String[] args ) { ApplicationContext applicationContext= SpringApplication.run(Application.class,args); Student student= (Student) applicationContext.getBean(Student.class); System.out.println("message:"+student.toString()); } }
application.yml内容:
#yml文件的配置格式是key:value student: name: 小明 age : 25
测试结果:
我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。