Spring boot @ConfigurationProperties 注解用起来可以这么优雅

Mar 11, 2019 阅读(2288)

标签: Java Spring

在做项目时,总是会碰到一下配置信息,配置信息的加载及注入看起来很不爽,代码看起来比较冗余不优雅。废话不多说上之前的代码:

application.yml 配置文件如下:

---
# 开发者账号相关信息
app:
    key: 1015796659
    secret: sandbox18d65256d7b325121d7d6b150
    geteway_url: https://gw.api.tbsandbox.com/router/rest
    authorize_url: https://oauth.tbsandbox.com/authorize
    access_token_url: https://oauth.tbsandbox.com/token
    callback_url: http://test.m-glory.net/qnh-txd-item/callback

对于业务层代码如下:

@Slf4j
@RestController
@RequestMapping("/callback")
public class CallbackController {

    @Autowired
    AuthService authService;

    @Value("${app.key}")
    private String APP_KEY;

    @Value("${app.secret}")
    private String APP_SECRET;

    @Value("${app.access_token_url}")
    private String AUTH_ACCESS_TOKEN_URL;

    @Value("${app.geteway_url}")
    private String AUTH_GETEWAY_URL;

    @Value("${app.callback_url}")
    private String CALLBACK_URL;

    @GetMapping(value = "/authorize", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String authorize(@RequestParam("code") String code, @RequestParam("state") String state) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("【授权回调】code: {},  state: {}", code, state);

        String signMethod = "md5";
        Map<String, String> props = new HashMap<String, String>();
        props.put("method", "taobao.top.auth.token.create");
        props.put("format", "json");
        props.put("code", code);
        props.put("app_key", APP_KEY);
        props.put("timestamp", sdf.format(new Date()));
        props.put("v", "2.0");
        props.put("sign_method", signMethod);

        String s = "{}";
        try {
            String sign = TaobaoSignUtil.signTopRequest(props, APP_SECRET, signMethod);
            props.put("sign", sign);
            s = WebUtils.doPost(AUTH_GETEWAY_URL, props, 30000, 30000);
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return s;
    }
}

 



最近这段时间公司在转型微服务,乘工作之余学习 Spring Cloud 时,发现 Spring Cloud 使用集中化实体类的方式并借助 @ConfigurationProperties 注解来实现将多个属性读取并自动封装成实体类(参见:EurekaClientConfigBean)来管理和使用,这种方式个人感觉更优雅,不废话,上修改后的代码:

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

/**
 * 应用程序配置bean
 */
@Data
@Component
@ConfigurationProperties("app")
public class ApplicationConfigBean {
    /**
     *  App Key
     */
    private String key;
    /**
     * App Secret
     */
    private String secret;
    /**
     * 公共网关接口地址
     */
    private String getewayUrl;
    /**
     * 回调接口地址
     */
    private String callbackUrl;
    /**
     * 获取授权code 接口地址
     */
    private String authorizeUrl;
    /**
     *  通过 code 换区 access token 接口地址
     */
    private String accessTokenUrl;
}

 

import com.taobao.api.internal.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import net.techfuser.qnhtxditem.auth.service.AuthService;
import net.techfuser.qnhtxditem.config.ApplicationConfigBean;
import net.techfuser.qnhtxditem.util.TaobaoSignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/callback")
public class CallbackController {

    @Autowired
    AuthService authService;

    @Autowired
    ApplicationConfigBean appConfig;


    @GetMapping(value = "/authorize", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String authorize(@RequestParam("code") String code, @RequestParam("state") String state) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("【授权回调】code: {},  state: {}", code, state);

        String signMethod = "md5";
        Map<String, String> props = new HashMap<String, String>();
        props.put("method", "taobao.top.auth.token.create");
        props.put("format", "json");
        props.put("code", code);
        props.put("app_key", appConfig.getKey());
        props.put("timestamp", sdf.format(new Date()));
        props.put("v", "2.0");
        props.put("sign_method", signMethod);

        String s = "{}";
        try {
            String sign = TaobaoSignUtil.signTopRequest(props, appConfig.getSecret(), signMethod);
            props.put("sign", sign);
            s = WebUtils.doPost(appConfig.getGetewayUrl(), props, 30000, 30000);
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return s;
    }

}

 

MongoDB学习园