Spring 中@ConfigurationProperties注解使用方法

@ConfigurationProperties注解作用:用于加载外部配置资源,填充对应字段。然后供应容器内其他bean使用。

和 @Value的区别:Spring 中@ConfigurationProperties注解使用方法_第1张图片

配置文件application-dev.yml:

email:
  foxmail:
    username: qq-username
    pwd: qq-pwd
  yahoo:
    username: 163-username
    pwd: 163-pwd

代码:

package com.example.demo;

import lombok.Data;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @description:
 * @author: xxx
 * @create: 2020-03-09 14:19
 **/
@RunWith(SpringRunner.class)
@SpringBootTest
@ConfigurationProperties(prefix = "email")
@Configuration
@PropertySource("classpath:application-dev.yml")// 指明配置文件
@Data
public class ConfigurationPropertiesDemo {
    private FoxMail foxmail = new FoxMail();
    private YaHoo yaHoo = new YaHoo();
    @Data
    class FoxMail{
        private String username;
        private String pwd;
    }
    @Data
    class YaHoo{
        private String username;
        private String pwd;
    }

    @Test
    public void demo1(){
        System.out.println(foxmail.username + "--" + foxmail.pwd);
        System.out.println(yaHoo.username + "--" + yaHoo.pwd);
    }
}

运行结果;

qq-username--qq-pwd
163-username--163-pwd

 

你可能感兴趣的:(java,SpringBoot)