0

I have this application.properties:

url.up=${url:http://localhost:8080/upload}

And I want to extract the url "http://localhost:8080/upload". How can I extract it?

I tried something like this, but the url is null:

String url = config.getPropertyValue("url");

Where getPropertyValue:

public String getPropertyValue(String propertyKey) {
    return properties.getProperty(propertyKey);
}
aSemy
  • 5,485
  • 2
  • 25
  • 51

4 Answers4

1

You should use @Value annotation. For example:

@Value("${url}")
private String url;

The url variable holds http://localhost:8080/upload.

Mustafa Çil
  • 766
  • 8
  • 15
1

U can use @Value in your class in your property file U can define

url.up=http://localhost:8080/upload

In Your class

@Value("${url.up}")
private String url;

then U can access the value using variable url

0

Unfortunately I do not know what class the config object is instatiated from which makes it hard to understand what the properties.getProperty() method call is doing. Therefore, I'll give you a a more general answer. As you are using Spring, you basically have two very elegant solutions to retrieve data from your application property files. If you just need a single value (as in your example the url.up field), then you would typically directly inject that value into the class that needs this data as in the following short Kotlin snippet (in java this would be very similar, just look up the @Value annotation on the internet).

@Component
class PropertyPrinter(
    @Value("\${url.up}") private val url: String
) {
    @PostConstruct
    fun postConstruct() {
        println("URL is: $url")
    }
} 

The other way would be to create a dedicated config class that hold a bunch logically connected fields and add the @ConfigurationProperties annotation. See here for a more in depth explanation.

yezper
  • 693
  • 3
  • 12
0

You should use @Value or appContext:

https://stackoverflow.com/a/29744955/21233858

  • I get null and this error java.lang.IllegalArgumentException: URI is not absolute if I use: ` @Value("${url}") String API;` – username1234565432 Feb 17 '23 at 13:29
  • your variable is named "url.up" not "url". becarefull of that. and the text after = is your value – bardia dorry Feb 19 '23 at 10:56
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 21 '23 at 13:54