注入的方式:
可以把需要注入的属性值写在yml中
然后创建组件类,通过注解@ConfigurationProperties(prefix = “”)的方式从yml中获取属性值,那么生成bean时,属性值就被注入其中。
@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {
private String mpAppId;
private String mpAppSecret;
private String openAppId;
private String openAppSecret;
private String mchId;
private String mchKey;
private String keyPath;
private String notifyUrl;
}
当使用第三方的组件的时候,无法使用@Component注解进行配置,这时可以使用JAVAConfig的方式来进行配置。@Bean修饰的方法为方法所返回的对象创建Bean,方法中可以为bean装配初始化属性。
@Configuration
public class WechatPayConfig {
@Autowired
private WechatAccountConfig wechatAccountConfig;
@Bean
WxPayConfig wxPayConfig(){
WxPayConfig wxPayConfig=new WxPayConfig();
wxPayConfig.setAppId(wechatAccountConfig.getMpAppId());
wxPayConfig.setAppSecret(wechatAccountConfig.getMpAppSecret());
wxPayConfig.setMchId(wechatAccountConfig.getMchId());
wxPayConfig.setMchKey(wechatAccountConfig.getMchKey());
wxPayConfig.setKeyPath(wechatAccountConfig.getKeyPath());
wxPayConfig.setNotifyUrl(wechatAccountConfig.getNotifyUrl());
return wxPayConfig;
}
@Bean
public BestPayServiceImpl bestPayService(){
BestPayServiceImpl bestPayService=new BestPayServiceImpl();
bestPayService.setWxPayConfig(wxPayConfig());
return bestPayService;
}
}