简体   繁体   English

无法使用 Spring 在 Controller 中获得价值

[英]Cannot get value in Controller using Spring

I had a Controller as shown below and after adding @Value("${code.url}") final String url , I encounter the following error:我有一个 Controller 如下所示,在添加@Value("${code.url}") final String url ,我遇到以下错误:

Could not resolve placeholder 'code.url' in value "${code.url}" at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean无法解析 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean 的值“${code.url}”中的占位符“code.url”

The problem is clearly related to the problem while reading code.url in application.yml .该问题显然与阅读application.yml中的code.url中的问题有关。


application.yml:应用程序.yml:

code:
   url: "https://www.gmail.com/"

controller: controller:

@RestController
@RequestMapping("/api/v1")
public class DemoController {

    private final DemoService demoService;
    private final Clock clock;
    private final String url;

    public DemoController(final DemoService demoService, final Clock clock,
                           @Value("${code.url}") final String url) {
        this.demoService = demoService;
        this.clock = clock;
        this.url = url;
    }

    //code omitted
}

I also tried to use @RequiredArgsConstructor in the controller, but it did not make any sense.我还尝试在 controller 中使用@RequiredArgsConstructor ,但没有任何意义。 So, how can I fix that problem?那么,我该如何解决这个问题呢?

Change your code to:将您的代码更改为:

@RestController
@RequestMapping("/api/v1")
public class DemoController {

    private final DemoService demoService;
    private final Clock clock;
    @Value("${code.url}")
    private final String url;

    public DemoController(final DemoService demoService, 
                          final Clock clock) {
        this.demoService = demoService;
        this.clock = clock;
     }

    //code omitted
}

change format from从改变格式

code:
url: "https://www.gmail.com/"

to

code:
  url: "https://www.gmail.com/"

You need to indent the yaml correctly:您需要正确缩进 yaml:

code:
   url: "https://www.gmail.com/"

otherwise the url is on the highest level and the property would be url and not code.url否则url处于最高级别,属性将为url而不是code.url

Use indentation in YAML file..在 YAML 文件中使用缩进..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM