我想将此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
。在这里我在做什么错了?
答案 0 :(得分:2)
获得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;
}
答案 1 :(得分:0)
我可能会误解您想要做什么,但是可以在您的应用程序设置中通过以下方式完成吗?
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
map.put("key5", "value5");
java.lang.System.getProperties().putAll(map);