首页 > 解决方案 > 为什么方法看不到构造函数中设置的值?(弹簧靴)

问题描述

我有一个这样的类 AuthorizationService:

@Service
public class AuthorizationService {

private final String code;
private final String client_id;
private final String redirect_uri;
private final String scope;
private final String show_dialog;

@Autowired
public AuthorizationService(
        @Value("${spotify-property.response_type}") String code,
        @Value("${spotify-property.client_id}") String client_id,
        @Value("${spotify-property.redirect_uri}") String redirect_uri,
        @Value("${spotify-property.scope}") String scope,
        @Value("${spotify-property.redirect_uri}") String show_dialog) {
    this.code = code;
    this.client_id = client_id;
    this.redirect_uri = redirect_uri;
    this.scope = scope;
    this.show_dialog = show_dialog;
    System.out.println(code); //works
}

public ResponseEntity<HttpHeaders> getSpotifyRedirectionCode() {
    HttpHeaders headers = new HttpHeaders();

    System.out.println(client_id); //doesn't work
    System.out.println(this.code); //does not work either
    System.out.println(redirect_uri);
    System.out.println(scope);
    System.out.println(show_dialog);

    //more code doesn't matter

    return new ResponseEntity<>(headers, HttpStatus.TEMPORARY_REDIRECT);
}

为什么这些变量在构造函数中可以,但在方法中为空,如何正确设置它们?还

@Value("${spotify-property.response_type}") 
private final String code;

也不起作用。

标签: springspring-boot

解决方案


您的类字段是最终的,因此无需您的配置值即可实例化。您可以像以前一样使用构造函数,也可以从字段中删除 final。


推荐阅读