Property map injection only via @Value
How to populate a value map using annotation @Values
, without defining anything in applicationContext.xml or any other XML file.
I'm using spring boot which doesn't have any XML files and I also don't want any XML files, so please don't tell me to declare any kind of beans property reader in XML etc.
Also, this is a property question - please don't suggest using a database to store data - this is not an answer and is not possible for my situation.
Also, I cannot use YAML either (due to deployment / operations requirements).
I've tried to declare this injection:
@Value("${myprop}")
Map<Integer, String> map;
And this one
@Value("${myprop.*}")
Map<Integer, String> map;
with these entries application.properties
:
myprop.1=One
myprop.2=Two
myprop.3=Three
and then tried
myprop[1]=One
myprop[2]=Two
myprop[3]=Three
But no good - just explodes with
Failed to create autowire field: ... Failed to resolve placeholder 'myprop'
I found a workaround with nested String[]
as specified key1:value1,key2:value2,...
, which then process the code, but I'd rather not do that because: a) it's more code, and b) the list will be quite long and all the pairs on the same line will be difficult to read and maintain.
Is there a way to automatically build a map from multiple properties?
I don't care what the property names are, what the field type or annotation is; I am just trying to enter one key / value pair for each property.
source to share
Not sure if this applies entirely to your scenario (you have Map<Integer, String>
, but at the end you say you just need a key-value pair in the map), but maybe this could give you some more ideas:
- Assuming the class
@Configuration
where the .properties file is loaded as an objectjava.util.Properties
:
@Configuration
public class Config {
@Bean(name = "mapper")
public PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("META-INF/spring/application.properties"));
return bean;
}
@Bean
public MyBean myBean() {
return new MyBean();
}
}
- the class
MyBean
where the onesProperties
introduced using SPeL are used:
public class MyBean {
@Value("#{mapper}")
private Map props;
public Map getProps() {
return props;
}
}
So in the end you are not using xml (of course), you need to use the PropertiesFactoryBean
.properties file to load and using @Value
Spring will inject Properties
into the map. Additional code (versus maybe @PropertySource
) is this PropertiesFactoryBean
, and you don't have to manually parse the values ββin your code (versus your workaround that introduces String[]
).
Hope it helps.
source to share
How about defining a bean in your Java config for this?
@Bean
public Map<Integer, String> myProps(Properties properties) {
Map<Integer, String> map = new HashMap<>();
// implement logic to populate map from properties
return map;
}
And in your class:
@Autowirded
Map<Integer, String> map;
source to share