我想将此XML配置转换为Java,但是有些人在寻找正确的方法上遇到了麻烦。
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System"/>
<property name="targetMethod" value="getProperties"/>
</bean>
</property>
<property name="targetMethod" value="putAll"/>
<property name="arguments">
<util:properties>
<prop key="key1">value1</prop>
<prop key="key2">value2</prop>
<prop key="key3">value3</prop>
<prop key="key4">value4</prop>
<prop key="key5">value5</prop>
</util:properties>
</property>
</bean>
它几乎可以正常工作,但是我收到关于
putAll
方法的错误。应该在Properties
对象上调用它,但是使用我的Java配置(见下文),它将尝试在MethodInvokingFactoryBean
对象上调用它。@Bean
public MethodInvokingFactoryBean getMethodInvokingFactoryBean() throws IOException {
final MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
final MethodInvokingFactoryBean target = new MethodInvokingFactoryBean();
target.setTargetClass(System.class);
target.setTargetMethod("getProperties");
methodInvokingFactoryBean.setTargetObject(target);
methodInvokingFactoryBean.setTargetMethod("putAll");
final Properties properties = new Properties();
properties.put("key1", "value1");
properties.put("key2", "value2");
properties.put("key3", "value3");
properties.put("key4", "value4");
properties.put("key5", "value5");
final PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setProperties(properties);
methodInvokingFactoryBean.setArguments(propertiesFactoryBean);
return methodInvokingFactoryBean;
}
所以我现在得到的错误是:
java.lang.NoSuchMethodException: org.springframework.beans.factory.config.MethodInvokingFactoryBean.putAll(org.springframework.beans.factory.config.PropertiesFactoryBean)
因为应该在putAll
对象上调用Properties
..我在这里做什么错的? 最佳答案
之所以得到NoSuchMethodException
是因为putAll
中没有MethodInvokingFactoryBean
方法。 putAll
方法来自Properties::putAll
,而Hashtable::putAll
是从this继承的。请参阅帖子。这是与您发布的xml类似的Java配置:
@Bean
public MethodInvokingFactoryBean getMethodInvokingFactoryBean() {
final MethodInvokingFactoryBean methodInvokingFactoryBean =
new MethodInvokingFactoryBean();
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
// add more key-value pairs
methodInvokingFactoryBean.setTargetObject(new Properties());
methodInvokingFactoryBean.setTargetMethod("putAll");
methodInvokingFactoryBean.setArguments(map);
return methodInvokingFactoryBean;
}