Spring MethodInvokingFactoryBean Example
By:Roy.LiuLast updated:2019-08-17
In Spring, you can use MethodInvokingFactoryBean to run a method, get the result and inject the result into another bean. This method invoker is very useful in XML configuration, but less use now in favor of annotation and Spring expression.
1. MethodInvokingFactoryBean
1.1 Example to get the current Java version.
Spring XML Configuration
<!-- 1. Run getProperties() method from java.lang.System --> <bean id="propsFromSystem" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetClass" value="java.lang.System" /> <property name="targetMethod" value="getProperties" /> </bean> <!-- 2. Run getProperty() method from propsFromSystem, with argument 'java.version' --> <bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject" ref="propsFromSystem" /> <property name="targetMethod" value="getProperty" /> <property name="arguments" value="java.version" /> </bean> <!-- 3. Inject the result into javaUtils bean --> <bean id="javaUtils" class="com.mkyong.web.JavaUtils"> <property name="javaVersion" ref="javaVersion" /> </bean>
package com.mkyong.web; public class JavaUtils { String javaVersion; public String getJavaVersion() { return javaVersion; public void setJavaVersion(String javaVersion) { this.javaVersion = javaVersion;
1.2 Java equivalent.
System.getProperties().getProperty("java.version")
2. MethodInvokingBean
Spring 4 introduced a new MethodInvokingBean to do the same thing, just without return any value.
2.1 Java code, a bit long, but it works.
public void startDBM() { MethodInvokingBean mBean = new MethodInvokingBean(); mBean.setTargetClass(DatabaseManagerSwing.class); mBean.setTargetMethod("main"); String[] args = new String[] { "--url", "jdbc:hsqldb:mem:testdb", "--user", "sa", "--password", "" }; mBean.setArguments(args); try { mBean.prepare(); mBean.invoke(); } catch (Exception e) { e.printStackTrace(); }
2.2 The MethodInvokingBean is good at XML configuration, but not in Java code, you can do the same thing with just one line of code.
public void startDBM() { DatabaseManagerSwing.main( new String[] { "--url", "jdbc:hsqldb:mem:testdb", "--user", "sa", "--password", "" });
2.3 XML example, show you how to pass a String [] array argument to MethodInvokingBean
<bean class="org.springframework.beans.factory.config.MethodInvokingBean"> <property name="targetClass" value="org.hsqldb.util.DatabaseManagerSwing" /> <property name="targetMethod" value="main" /> <property name="arguments"> <list> <value>--url</value> <value>jdbc:derby:memory:dataSource</value> <value>--user</value> <value>sa</value> <value>--password</value> <value></value> </list> </property> </bean>
References
From:一号门
Previous:Spring embedded database examples
COMMENTS