【Java】【SpringBoot】读取配置文件(appliation.yml)的值
这里叙述4中读取配置文件(application.yml)方法
application.yml配置如下:
# 测试数据(用于读取数据文件值) student: name: lisi age: 13 name: zhangsan
使用@value注解
@SpringBootTest public class ApplicationTest { @Value("${student.name}") private String name; /** * Value注解 * @author lyj * @date 2024-09-06 */ @Test public void test(){ System.out.println(name); } }
结果
使用@ConfigurationProperties注解
1 @Component 2 @ConfigurationProperties(prefix = "student") 3 public class MyBean { 4 5 private String name; 6 private String age; 7 8 public String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 public String getAge() { 17 return age; 18 } 19 20 public void setAge(String age) { 21 this.age = age; 22 } 23 }
@SpringBootTest public class ApplicationTest {
@Autowired private MyBean myBean; /** * Value注解 * @author lyj * @date 2024-09-06 */ @Test public void test(){ System.out.println(myBean.getName()); System.out.println(myBean.getAge()); }
}
使用Spring代理的Environment对象
@SpringBootTest public class ApplicationTest { @Autowired private Environment environment; /** * 使用EnvironMent对象 * @author lyj * @date 2024-09-06 */ @Test public void test2(){ System.out.println(environment.getProperty("student.name")); System.out.println(environment.getProperty("student.age")); } }
返回结果
使用:使用Spring代理的ApplicationContext对象
@SpringBootTest public class ApplicationTest { @Autowired private ApplicationContext applicationContext;/** * 使用ApplicationContext对象 * @author lyj * @date 2024-09-06 */ @Test public void test3(){ Environment environment1 = applicationContext.getEnvironment(); System.out.println(environment1.getProperty("student.name")); System.out.println(environment1.getProperty("student.age")); } }
有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。