springboot使用PropertySource和Value注解加载指定的属性文件

springboot使用PropertySource和Value注解加载指定的属性文件

1.作用

通过@PropertySource注解可以把配置文件加载进来,然后使用@Value获取其中的属性值

2.实例

假如想获取a.properties中

步骤

1.建立配置类

@Configuration
//classpath:classpath 就是针对src/main/java或者是src/main/resources  下面都是classpath 下面
//指定配置文件的位置
@PropertySource("classpath:a.properties")
public class A {
    @Value("${a.name}")
    private String name;
    @Value("${a.age}")
    private String age;
    public String print(){
        return name + "-" + age;
    }
}

2.创建配置文件a.properties

a.name=1
a.age=18

如果这样

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ba70Fd46-1619075227708)(C:\Users\14612\AppData\Roaming\Typora\typora-user-images\image-20210422150336584.png)]

则是配置类中@Value注解未使用$,或者字段未对应

3.创建测试类读取配置


import com.dfinfo.pojo.A;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SmalabelBackendServiceApplicationTests {
@Autowired
    A a;
    @Test
    void contextLoads() {
        System.out.println(a.print());
    }

}

4.执行效果

打印效果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值