SpringBoot通过注解ConfigurationProperties可以将application.yaml的参数注入到类中,但是笔者踩了个大坑
@Component
@Data
@ConfigurationProperties("project.wechat")
public class WeChatSchedule {
    private String appId;
    private String secret;
    @Resource
    private RestTemplate restTemplate;
    public void getAccessToken() {
        final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
        String url = UriComponentsBuilder
                .fromHttpUrl(GET_TOKEN_URL)
                .queryParam("appid", appId)
                .queryParam("secret", secret)
                .toUriString();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response.getStatusCode().is2xxSuccessful()) {
            String body = response.getBody();
            System.out.println("body=" + body);
        }
    }
}
在一个腾讯获取AccessToken的类中,我将方法名称写成getAccessToken后,SpringBoot一直报错,无法注入appId,secret:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under ‘project.wechat’ to com.samele.epay.schedule.WeChatSchedule:
Reason: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under ‘project.wechat’ to com.samele.epay.schedule.WeChatSchedule
Action:
Update your application’s configuration
解决办法是:更新你的application配置
但是这个描述实在是坑爹,调整了一宿,修改了类名,修改了参数名,改了驼峰写法等等。一直报错。
后来发现把getAccessToken换个名字,比如flushAccessToken之后,就注入成功了。
神特么逻辑,看来以后还要注意,有参数注入的时候尽量避免get和set起始的方法。避免被SpringBoot错误的识别。
        
                            
评论(已关闭)
评论已关闭