Spring properties to map
程序员文章站
2022-06-08 15:41:10
...
Spring properties to map
一个key-value形式的properties文件 以Map的形式注入到Spring的bean中
properties文件形式
RF09001=fooService#method1#name,phone
spring 配置
<bean id="noMethodMap" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:foo.properties"/>
</bean>
注入到Bean中
@Resource(name="noMethodMap")
private Map<String, String> noMethodMap;
其他
如何定位注入源码
修改为一个不存在的资源名称
@Resource(name="nonexist")
此时启动会报错
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'nonexist' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:522)
可知是在哪里注入的了
在哪里将PropertiesFactoryBean转成Map
同样的处理方式 将注入变量修改成一个错误的类型 查看错误信息即可
private String noMethodMap; // map --> String
启动会报错
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'noMethodMap' is expected to be of type 'java.lang.String' but was actually of type 'java.util.Properties'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:378)
就知道是在哪里进行类型转换的了
如果想对properties-->Map做一下自定义的处理呢
如RF09001-RF09010对应的都是同一个value
RF09001-RF09003=fooService#method1#name,phone
但是想Map中的实际形式为
RF09001=fooService#method1#name,phone
RF09002=fooService#method1#name,phone
RF09003=fooService#method1#name,phone
继承PropertiesFactoryBean
覆盖createProperties
即可
public class MyPropertiesFactoryBean extends PropertiesFactoryBean{
@Override
protected Properties createProperties() throws IOException {
Properties properties = super.createProperties();
Enumeration<String> propertyNames = (Enumeration<String>) properties.propertyNames();
while(propertyNames.hasMoreElements()){
String name = propertyNames.nextElement();
if(name.matches("\\w+-\\w+")){
String rawName = name;
String[] split = rawName.split("-");
Integer start = Integer.valueOf(split[0].substring(2));
Integer end = Integer.valueOf(split[1].substring(2));
for (int i = start; i <= end; i++) {
properties.setProperty("RF" + i, properties.getProperty(rawName));
}
}
}
return properties;
}
spring配置改成
<bean id="noMethodMap" class="com.foo.app.util.MyPropertiesFactoryBean">