简体   繁体   中英

How to populate property of spring bean from static method

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 class="com.example.ClassA"
    p:name=//Utils.getRandomName()
    p:age="33"
/>

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

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

<bean class="com.example.ClassA"
    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 class="com.example.ClassA"
    p:name="#{ T(com.example.Utils).getRandomName() }"
    p:age="33"
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM