Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Parameter to ApplicationContext

I my application I have an application-context.xml. Now I am instantiating The ApplicationContext as:

ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

Is it possible to pass parameter through this instantiation so that those parameters could be used to initialize some properties of some beans?

PS: Not using property file. As the parameters are generated run time, like exicutable jar's location, system architecture, os name etc which is variable.

like image 489
Tapas Bose Avatar asked Jul 05 '26 22:07

Tapas Bose


1 Answers

You can use the PropertyPlaceholderConfigurer in your applicationContext.xml

<context:property-placeholder location="classpath:my.properties"/>

This allows you to reference properties directly in your bean declarations using syntax ${myProperty} assuming the properties file contains a property named myProperty.

A sample how you can use such a property:

<bean id="foo" class="com.company.Foo">
   <property name="bar" value="${myProperty}"/>
</bean>

Another alternative could be based on the @Value annotation powered by SpEL.

like image 114
Johan Sjöberg Avatar answered Jul 08 '26 11:07

Johan Sjöberg



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!