- 直接注入
- 写一个专门的配置类
目的:有些属性方便写成配置文件方便更改
- 方法一:直接注入
@RestController
@RequestMapping("api/v1/test")
@PropertySource({"classpath:pay.properties"})
public class TestController {
@Value("${wxpay.appid}")
private String payAppid;
@Value("${wxpay.secret}")
private String paySecret;
@Autowired
private WXConfig wxConfig;
@GetMapping("get_config")
public JsonData testConfig(){
Map<String,String> map = new HashMap<>();
map.put("appid",payAppid);
map.put("secret",paySecret);
return JsonData.buildSuccess(map);
}
}
1、Controller上面配置 @PropertySource({“classpath:resource.properties”})
2、增加属性 @Value(“${test.name}”) private String name;
- 方法二:写一个专门的配置类
@Configuration
@PropertySource(value="classpath:pay.properties")
public class WXConfig implements Serializable {
@Value("${wxpay.appid}")
private String payAppid;
@Value("${wxpay.secret}")
private String paySecret;
@Value("${wxpay.mechid}")
private String payMechId;
public String getPayAppid() {
return payAppid;
}
public void setPayAppid(String payAppid) {
this.payAppid = payAppid;
}
public String getPaySecret() {
return paySecret;
}
public void setPaySecret(String paySecret) {
this.paySecret = paySecret;
}
public String getPayMechId() {
return payMechId;
}
public void setPayMechId(String payMechId) {
this.payMechId = payMechId;
}
}
@GetMapping("get_config")
public JsonData testConfig(){
Map<String,String> map = new HashMap<>();
map.put("appid",wxConfig.getPayAppid());
map.put("secret",wxConfig.getPaySecret());
map.put("mechid",wxConfig.getPayMechId());
return JsonData.buildSuccess(map);
}
1、添加 @Component 注解;
2、使用 @PropertySource 注解指定配置文件位置;
3、使用 @ConfigurationProperties 注解,设置相关属性;
4、必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。
@Autowired private ServerSettings serverSettings;