spring @PropertySource 搭配 @ConfigurationProperties从配置文件设置属性
代码示例以及说明
@Component
@PropertySource("classpath:ali.properties")
@ConfigurationProperties(prefix = "ali.pay")
@Data
public class AliPayConfig {
private String appId;
/**
* 生成公钥时对应的私钥(填自己的)
*/
private String privateKey;
/**
* 生成公钥
*/
private String publicKey;
/**
* 签名方式
*/
private String signtype;
/**
* 编码
*/
private String charset;
/**
* 返回格式
*/
private String format;
/**
* 支付宝网关(注意沙箱alipaydev,正式则为 alipay)不需要修改
*/
private String gatewayUrl;
/**
* 服务器地址前缀
*/
private String baseUrl;
/**
* 服务器异步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
*/
private String notifyUrl;
/**
* 页面跳转同步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 商户可以自定义同步跳转地址
*/
private String returnUrl;
}
以上是一个支付宝的配置类,@PropertySource
说明读取的属性文件源。@ConfigurationProperties(prefix = "ali.pay")
指定前缀为ali.pay
。 @Data
是lombok
标签,替代setter和getter方法。
配置文件ali.properties
示例:
ali.pay.appId=1
这样你就可以在你的service类里面依赖注入该配置类并使用了。 好处是这样的配置单独放在一个文件里面,清晰易维护。