I have a Map<String, String>
and I would like to tell Spring to use this when creating beans and resolving property placeholders. What is the easiest way to do this? Here is an example:
@Component
public class MyClass {
private String myValue;
@Autowired
public MyClass(@Value("${key.in.map}") String myValue) {
this.myValue = myValue;
}
public String getMyValue() {
return myValue;
}
}
public static void main(String[] args) {
Map<String, String> propertyMap = new HashMap<>();
propertyMap.put("key.in.map", "value.in.map");
ApplicationContext ctx = ...;
// Do something???
ctx.getBean(MyClass.class).getMyValue(); // Should return "value.in.map"
}
The context:property-placeholder tag is used to externalize properties in a separate file. It automatically configures PropertyPlaceholderConfigurer , which replaces the ${} placeholders, which are resolved against a specified properties file (as a Spring resource location).
A Placeholder is a predefined location in a JSP that displays a single piece of web content at a time that is dynamically retrieved from the BEA Virtual Content Repository.
properties in spring boot. Using placeholders, Spring Boot allows you to reuse values in the application properties file. Spring boot placeholder can be used to configure a key value that is the same as another key value or to create a value using another key value.
Spring provides a MapPropertySource
which you can register with your ApplicationContext
's Environment
(you'll need a ConfigurableEnvironment
which most ApplicationContext
implementations provide).
These registered PropertySource
values are used by the resolvers (in order) to find a value for your placeholder names.
Here's a complete example:
@Configuration
@ComponentScan
public class Example {
@Bean
public static PropertySourcesPlaceholderConfigurer configurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
// can also add it here
//configurer.setPropertySources(propertySources);
return configurer;
}
public static void main(String[] args) {
Map<String, Object> propertyMap = new HashMap<>();
propertyMap.put("key.in.map", "value.in.map");
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
MapPropertySource propertySource = new MapPropertySource("map-source", propertyMap);
ctx.getEnvironment().getPropertySources().addLast(propertySource);
ctx.register(Example.class);
ctx.refresh();
MyClass instance = ctx.getBean(MyClass.class);
System.out.println(instance.getMyValue());
}
}
@Component
class MyClass {
private String myValue;
@Autowired
public MyClass(@Value("${key.in.map}") String myValue) {
this.myValue = myValue;
}
public String getMyValue() {
return myValue;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With