@Value注解,yml配置文件内容的获取

85 阅读1分钟

yaml配置文件的编写和其内容的获取

可以在yaml中编写任意缩进和单词(除spring中已经固定的),都可以在项目中使用@Value注解来获取到

email:
	user: 2690152257
	password: 123456

获取

版本一

@Component
public class Email{
    @Value("${email.user}")
    public String user;

    @Value("${email.password}")
    public String password;
}

版本二

@Component
@ConfigurationProperties(prefix="email")
public class Email{
    public String user;
    public String password;
}

版本二的prefix=前缀,前缀必须要与配置文件中的前缀一致,配置文件键名与成员变量名一致。需要加@Component才能将其注入到IOC容器之中。

另外:如果不在其上加Component注解,也可以使用@EnableConfigurationProperties注解来使@ConfigurationProperties生效: 在启动类或者Service、mapper类上添加如下注解

@EnableConfigurationProperties({Email.class})