Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject an external property into Spring context

Tags:

java

spring

I have three apps in a Spring 2.5 managed project that share some code and differ in details.

Each application has a property (java.lang.String) which is used before the application context is built.

Building the app context takes some time and cannot happen first. As such, it's defined in each individual application. This property is duplicated in the context definition since it is also needed there. Can I get rid of that duplication?

Is it possible to inject that property into my application context?

like image 953
DerMike Avatar asked Aug 25 '10 10:08

DerMike


People also ask

How property values can be injected directly into your beans in Spring boot?

Property values can be injected directly into your beans using the @Value annotation, accessed via Spring's Environment abstraction or bound to structured objects via @ConfigurationProperties . Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values.

How do I configure externalize in Spring boot?

Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.


1 Answers

Have a look at PropertyPlaceholderConfigurer.

The Spring documentation talks about it here.

<bean id="myPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:my-property-file.properties"/>
    <property name="placeholderPrefix" value="$myPrefix{"/>
</bean>

<bean id="myClassWhichUsesTheProperties" class="com.class.Name">
    <property name="propertyName" value="$myPrefix{my.property.from.the.file}"/>
</bean>

You then have reference to that String to anywhere you'd like in your application context, constructor-arg, property etc.

like image 83
Noel M Avatar answered Oct 23 '22 11:10

Noel M