Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass UniqueID as constructor args to a spring bean

I am a new to spring. I have a bean class with a constructor having single parameter, a uniqueId.

void Sample(String uniqueId){
      this.uniqueId = uniqueId;
}

the bean doesn't have any default constructor. I require this id for some bussiness logic. this uniqueID needs to be UUID.randomUUID().toString().

How can pass this to the bean from the bean configuration xml.

<bean id="Sample" class="com.scribe.dao.Sample">
     <constructor-arg  value="UUID.randomUUID().toString()"/>               
</bean>

this doesn't work. What are my other options? I have also seen an example like this in another post on stackoverflow.<constructor-arg value="uniqueId"/> but the same didnot work for me.Is there any easyway to do this. any help appreciated.

like image 387
arvin_v_s Avatar asked Dec 13 '25 21:12

arvin_v_s


1 Answers

You need to make use of Spring Expression Language (SpEL) as illustrated here

The bean definition should look like below

<bean id="Sample" class="com.scribe.dao.Sample">
    <constructor-arg  value="#{ T(java.util.UUID).randomUUID().toString() }"/>               
</bean>
like image 74
Bond - Java Bond Avatar answered Dec 16 '25 10:12

Bond - Java Bond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!