Home > Software design >  How to populate property of spring bean from static method
How to populate property of spring bean from static method

Time:04-12

I would like to know, how can I populate spring bean property from static method. This is my example. I have ClassA and Utils with static method:

    public class ClassA{
        private String name;
        private int age;
        
        //getters setters
    }
    
    public class Utils{
        static String getRandomName(){
            return "someRandomName"; //here is some logic returning random string
        }
    }

I would like to create bean from ClassA with usage of the Utils static method getRandomName. Like this:

<bean 
    p:name=//Utils.getRandomName()
    p:age="33"
/>

,but I do not know how to call static method from the application-context.xml

CodePudding user response:

you can try it like this.

<bean id="myBean"  factory-method="getRandomName">
   <!-- invoke here -->
</bean> 

CodePudding user response:

while creating bean spring calls the setter methods of specified fields of object. So you can call static method in setName() method like this.

public void setName(){
this.name = getRandomName();
}

CodePudding user response:

There is a special value that produces random values. random.value will produce random alphanumeric strings. So your bean might look like:

<bean 
    p:name="${random.value}"
    p:age="33"
/>

If there is extra logic going on in your getRandomName(), then you can use Spring Expression Language (SpEL) to execute expressions. For example:

<bean 
    p:name="#{ T(com.example.Utils).getRandomName() }"
    p:age="33"
/>
  • Related