springboot 将配置文件中的配置读取为properties配置类

1、确保依赖

  

 <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-configuration-processor </artifactId>
            <optional> true </optional>
        </dependency>

  

2、配置类编写,注意注解

  

package com.detech.qydxxpt;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author YunguiZheng
 */
@ConfigurationProperties(prefix = SmsProperties.PREFIX)
@Data
public class SmsProperties {

    public static final String PREFIX ="sms" ;
    /**
     * 服务地址
     */
    public  String url ;
    /**
     * 用户名
     */
    public  String username;
    /**
     * 密码
     */
    public  String password ;
    /**
     * 固定字符串
     */
    public  String key ;
    /**
     * 接入KEY
     */

    public  String jrKey ;
    /**
     * 业务代码
     */

    public  String ywdm ;

}

 3、重要:在启动类上打上注解

@EnableConfigurationProperties(SmsProperties.class)   
package com.dflzm.user;

import com.detech.qydxxpt.SmsProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;


@SpringBootApplication
@EnableConfigurationProperties(SmsProperties.class)
public class ApiUserCenterApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiUserCenterApplication.class, args);
    }

}

 4、配置文件yml格式如下

  

sms:
  url: http://xxx.com
  username: xxx
  password: xxx
  key: 6798FEB3-71E5-48B6-A49B-1E1F33BAA14B
  jrKey: "0000088"
  ywdm: xxx

 5、测试是否配置成功

  

package com.dflzm.user;

import com.detech.qydxxpt.SmsProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApiUserCenterApplicationTests {

    @Resource
    SmsProperties smsProperties;

    @Test
    public void  contextLoads() {
        System.err.println(smsProperties.toString());
    }

}

  输出:  

[2020-06-16 10:26:44] [INFO ][com.alibaba.nacos.client.naming:61]-- [LISTENER] adding DEFAULT_GROUP@@dflzm-backend-service with to listener map
SmsProperties(url=http:xxx, username=xxx, password=xxx, key=6798FEB3-71E5-48B6-A49B-1E1F33BAA14B, jrKey=xxx, ywdm=xxx)

  

 参考:

  https://www.cnblogs.com/Guhongying/p/10848251.html

 

 
原文地址:https://www.cnblogs.com/irobotzz/p/13139618.html