我们经常将一些固定的数值(魔法值)写入到配置文件properties中,在读取properties文件里的内容注入到Spring容器中,进行代码的优化。
1、材料准备
# 在resources目录文件夹下建huanxin.properties文件,内容如下
tanhua.huanxin.url=http://a1.easemob.com/
tanhua.huanxin.orgName=1126210210111195
tanhua.huanxin.appName=tanhua
tanhua.huanxin.clientId=YXA2DKjuaaM4QiqS5hVl9BMjJw
tanhua.huanxin.clientSecret=YXA4uCCG_qCZxgUlyyrYBZj2bFJikJU
2、编写配置类,注入Spring容器中:
package com.tanhua.sso.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:huanxin.properties")
@ConfigurationProperties(prefix = "tanhua.huanxin")
@Data
public class HuanXinConfig {
private String url;
private String orgName;
private String appName;
private String clientId;
private String clientSecret;
}
3、通过配置类读取数据信息
@Autowired
private HuanXinConfig huanXinConfig;
String url=huanXinConfig.getUrl(); //url为http://a1.easemob.com/