Home > Net >  Cannot get value in Controller using Spring
Cannot get value in Controller using Spring

Time:12-17

I had a Controller as shown below and after adding @Value("${code.url}") final String url, I encounter the following error:

Could not resolve placeholder 'code.url' in value "${code.url}" at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean

The problem is clearly related to the problem while reading code.url in application.yml.


application.yml:

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

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. So, how can I fix that problem?

CodePudding user response:

You need to indent the yaml correctly:

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

otherwise the url is on the highest level and the property would be url and not code.url

CodePudding user response:

change from

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

to

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

Also, Make sure the location & availability of the appropriate yml file eg: enter image description here

CodePudding user response:

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
}

CodePudding user response:

Use indentation in YAML file ..

  • Related