首页 > 编程语言 >【Java】【SpringBoot】读取配置文件(appliation.yml)的值

【Java】【SpringBoot】读取配置文件(appliation.yml)的值

时间:2024-09-06 14:25:55浏览次数:9  
标签:Java name 配置文件 age System println out public SpringBoot

这里叙述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 }
MyBean.java 注释语句
@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"));
    }
}

 

标签:Java,name,配置文件,age,System,println,out,public,SpringBoot
From: https://www.cnblogs.com/luyj00436/p/18400067

相关文章