Get the value from the property file dynamically using Environment.
spring boot 2.0.3.RELEASE
application.properties
sample.name=hoge
sample.age=20
Inject the Environment and call the getProperty method.
SampleProperty.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
// @Specify the location of the property file with PropertySource
@PropertySource("classpath:/application.properties")
public class SampleProperty {
//Inject Environment
@Autowired
private Environment env;
public String get(String key) {
//Get property value from Environment
return env.getProperty("sample." + key);
}
}
Get the value from the Configuration class with the path included in the URL as the key.
SampleController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@Component
@RestController
public class SampleController {
@Autowired
private SampleProperty prop;
@GetMapping(path = "/user/{key}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getUser(@PathVariable String key) {
String result = prop.get(key);
if (result == null) {
result = "The value could not be obtained.";
}
return result;
}
}
Access http: // localhost: 8080 / user / name from your browser
Access http: // localhost: 8080 / user / age from your browser
Recommended Posts