LucaA
LucaA

Reputation: 713

Invoke static method from spring config

Is it possible to invoke static method in Spring configuration file?

public MyClass {

   public static void staticMethod() {
       //do something
   }

}
<bean id="myBean" class="MyClass">
   <!-- invoke here -->
</bean>

Upvotes: 19

Views: 39504

Answers (4)

Cloud
Cloud

Reputation: 993

If you are using annotations for spring configuration you can add the following method into your @Configuration class:

@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
    MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
    methodInvokingFactoryBean.setStaticMethod("MyClass.staticMethod");

    return methodInvokingFactoryBean;
}

Upvotes: 0

jbarrameda
jbarrameda

Reputation: 1997

Try something like this:

<!-- call static method -->
<bean id="test" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass" value="MyClass" />
    <property name="targetMethod" value="staticMethod" />
    <property name="arguments">
        <list>
            <value>anArgument</value>
        </list>
    </property>
</bean>

Remove arguments as you might not need them.

Taken from https://gist.github.com/bulain/1139874

I was needing to call a static method. The above code worked fine.

This might be useful as well: How to make spring inject value into a static field.

Upvotes: 4

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

try this

<bean id="b1" class="org.springframework.beans.factory.config.MethodInvokingBean">
    <property name="staticMethod" value="MyClass.staticMethod" />
</bean>

see http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/MethodInvokingBean.html

Upvotes: 17

Hank Lapidez
Hank Lapidez

Reputation: 2025

  1. When the static method creates an instance of MyClass you an do it like this

config

<bean id="myBean" class="MyClass" factory-method="staticMethod">
   <!-- invoke here -->
</bean>

code

public static MyClass staticMethod() {
       //create and Configure a new Instance
}
  1. If you want the method only to be called on bean instantiation spring can't do it this way.

config

<bean id="myBean" class="MyClass" init-method="init">
   <!-- invoke here -->
</bean>

code

public static void staticMethod() {
       //create and Configure a new Instance
}

public void init() {
     staticMethod();
}

Upvotes: 23

Related Questions