Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 614
LucaA Avatar asked Dec 04 '14 14:12

LucaA


People also ask

How do you invoke a static method?

Invoking a public static Method Once we hold the method object, we can invoke it simply by calling the invoke method. It's worthwhile to explain the first argument of the invoke method. If the method is an instance method, the first argument is the object from which the underlying method is invoked.

Can you invoke a static method from an instance?

A static method in Java (also called class method) is a method that belongs to the class and not the instance. Therefore, you can invoke the method through the class instead of creating an instance first and calling the method on that instance.

Can a Spring Bean have static methods?

Yes, A spring bean may have static methods too.

What is static method in Spring?

Static factory methods are those that can return the same object type that implements them. Static factory methods are more flexible with the return types as they can also return subtypes and primitives too. Static factory methods are used to encapsulate the object creation process.


2 Answers

  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();
}
like image 174
Hank Lapidez Avatar answered Sep 28 '22 10:09

Hank Lapidez


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

like image 25
Evgeniy Dorofeev Avatar answered Sep 28 '22 08:09

Evgeniy Dorofeev