Kevin
Kevin

Reputation: 45

Using Java and Spring Boot and my @Value annotation for my application-dev.properties is not being resolved?

This is my very first question so I apologize if it is not specific enough (please be gentle haha) and I have already gone through documentation, but I am new to the field and none of it helped.

I am making a simple project that uses Java 18 and Spring Boot to make a call to an external API call and I want to hide my API key that I use for obvious reasons.

As of right now, I have an application-dev.properties file in my resources directory with the following (I am making up the actual key for security) and I have application-dev.properties in my .gitignore file so it doesn't get committed:

api-key=someText

And I am trying to use that value in my controller like so:

@RestController
public class ImageController {

    @Value("${api-key}")
    private String API_KEY;

    @RequestMapping(value = "/image")
    public List<String> getImages(@RequestParam(defaultValue = "4") String request) {

        String url = "https://api.nasa.gov/planetary/apod?" + API_KEY + request;
        RestTemplate restTemplate = new RestTemplate();

The error I am receiving is this:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'imageController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'api-key' in value "${api-key}"

Thanks in advance!

Upvotes: 1

Views: 715

Answers (2)

DwB
DwB

Reputation: 38328

As mentioned in the other answer, the name of the application-dev.properties file requires that you activate the "dev" profile or Spring Boot will never read it and the values therein will not be available to your @Value annotation.

Here is a link to a Baeldung article that discusses Spring Boot profiles: Spring Boot Profiles at Baeldung (I am not associated with Baeldung, I just like much of their stuff).

If you are not planning to use profiles in your application, change the name of the properties file to "application.properties".

Upvotes: 2

YJR
YJR

Reputation: 1202

As you mentioned you are using application-dev.properties therefore you have to do profiling correctly. In your application.properties add spring.profiles.active=dev to activate dev profile.

Upvotes: 1

Related Questions