获取配置文件内容@Value和@ConfigrationProperties

1.配置文件内容

test:
  token: eykhisyfsdfhjkdsfiowefjj
  uid: 110
  user_name: admin
  password: 123456

2.使用@Value注解

  • @Value("${变量}")
@Value("${test.user_name}")
    private String userName;
  • @Value("#{表达式}"),可以使用spel表达式
@Value("#{12*2}")
private Integer sum;
 # 此时sum的值为24

3.使用@ConfigurationProperties注解

  • 先封装一个实体类,将属性赋值,利用IOC实现依赖注入。实体类和配置文件支持驼峰转换
@Data
@Component
@ConfigurationProperties(prefix = "test")
public class Properties {
    
    
    private String token;
    private String uid;
    private String userName;
}
  • 实现依赖注入,获取变量值
@Autowired
    private PropertiesTest properties;

@Test
    void testYml(){
    
    
        System.out.println(properties.getToken());
        System.out.println("++++++++++");
        System.out.println(properties.getUserName());
    }

猜你喜欢

转载自blog.csdn.net/Proxbj/article/details/123795103