Spring common property reference with different value per application - java

I have a bean which is used across all projects (different war files).
That particular bean requires a property appname (to know which app is using the bean).
How can i configure this?
I tried passing the value in the following way:
<bean id="appNameProperty" class="java.util.Properties">
<property name="appName" value="app1" />
</bean>
Bean definition:
<bean id="someClass" class="someClass">
<property name="appName" value="#{appNameProperty.appName}" />
</bean>
Where appName is supposed to be a String value.
I get the following exception while deploying my app:
Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'appName' of bean class [java.util.Properties]: Bean property 'appName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

To avoid the VM arguments you could use the property placeholder configurer as mentioned above. If the app name is fixed for every application and you are using war-files everywhere you could add e.g. "/WEB-INF/config" to the list of the properties location and place there a properties file containing the app-name:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- further locations -->
<value>WEB-INF/config/*.properties</value>
<!-- further locations -->
</list>
</property>
<!-- further configuration as needed -->
</bean>

This may help you.
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="yourBean" class="path.to.your.BeanClass">
<property name="appName" value="#{systemProperties['appName']}"/>
</bean>
All you need to do is pass VM arguement -DappName=abcApp while starting the app.
ref PropertyPlaceHolderConfigurer

Related

Does Spring supports nested SpEL expressions?

This is my properties file:
base1.jdbc.password=pass1
base2.jdbc.password=pass2
base3.jdbc.password=pass3.
I have an environment variable called %DATABASE% which can be either base1 or base2 or base3.
How can i read the password property of the database stored in the environment variable? i thought about something like:
<property name="password" value="${#{systemProperties['DATABASE']}.jdbc.password}"/>.
but not sure if it's correct.
Add property place holder
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:xxxxx.properties</value>
</list>
</property>
</bean>
Then
<bean id="bean" class="xxx.class">
<property name="password" value="#{systemProperties['DATABASE']}.jdbc.password"/>
</bean>
Use the following configuration in your application context xml
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>##YOUR PROPERTIES FILE NAME###</value>
</property>
</bean>
You can get the details from an associated question (How do you configure a Spring bean container to load a Java property file?)
The description of the PropertyPlaceholderConfigurer is given here(http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html)
Use the name of the properties file that you have in the <value> tag
Following is an example of how I have used the properties in my sample project. I have a bean called processRetryPolicy with the properties with are loaded from the properties file.
<bean id='processRetryPolicy' class='com.poc.process.model.ProcessRetryPolicy' >
<property name="isActive" value="${process.executor.conn.retry.policy.isActive}"/>
<property name="intervalType" value="${process.executor.conn.retry.interval.type}"/>
<property name="intervalvalue" value="${process.executor.conn.retry.interval.value}"/>
<property name="retryPolicy" value="${process.executor.conn.retry.default.policy}"/>
</bean>
The properties are defined in the properties file as
process.executor.conn.retry.policy.isActive = true
process.executor.conn.retry.interval.type = HOUR
process.executor.conn.retry.interval.value = 1
process.executor.conn.retry.default.policy = Retry
To add the environment properties I had used the following in one of the spring batch applications:-
<property name="environment" value="#{jobParameters['env.type']}"/>
The environment type was being passed as a runtime parameter as follows
java -Xmx12288m -D<<List of Params and Values>> env.type=$env
Another way of doing it in spring core is using the spring expression language (http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/expressions.html)
Your expression looks correct.

java.util.Properties: How do I retrieve values from Properties in spring config xml

I have a java.util.Properties object which has few key value pairs in it. I am trying to use this Property object in the spring configuration file i.e. define the key in the spring config and during runtime, it should get the value from the properties object.
For ex:
<bean id="test" class="com.sample.Test">
<constructor-arg value="${PROPERTY_KEY} />
</bean>
Now during the runtime, the constructor should get the value that is present in the Property object.
Is there a way to get this done ?
Note: I do not want to use config.properties here. Looking to use java.util.Properties
Thanks,
Rahul
<context:property-placeholder location="classpath:placeholder.properties"/>
or
<bean id="properties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:<file-name>.properties" />
</bean>
First you have to create bean to access your property file, like below
<bean id="appProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="singleton" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath*:localhost-mysql.properties</value>
<value>classpath*:mail-server.properties</value>
</list>
</property>
</bean>
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="appProperties" />
</bean>
Next you can access Key-Value pair from your property files, like below
<bean id="mailServerSettings" class="com.ratormonitor.app.context.EmailSettings">
<property name="host" value="${mail.server.host}" />
<property name="port" value="${mail.server.port}" />
<property name="username" value="${mail.server.username}" />
<property name="password" value="${mail.server.password}" />
<property name="requestContextPath" value="${request.context.path}" />
</bean>
Hope this code will solve your problem.
You can use Spring Expression Language (SpEL) to get a java object value in spring configuration xml file.
An example :
<property name="misfireInstruction"
value="#{T(org.quartz.CronTrigger).MISFIRE_INSTRUCTION_FIRE_ONCE_NOW}"/>
So this is how I did:
As I said I had a java.util.Properties object. I then created a CustomProperty class which extended PropertySource>
public class CustomPropertySource extends PropertySource<Map<String, Object>>
Then in my main class I did the following:
AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[] {springConfigLocation, false);
context.getEnvironment().getPropertySources.addlast(new CustomPropertySource("custom", propertiesObject));
conext.refresh();
And then in the spring config file, I had to add this:
<context: property-placeholder ignore-unresolvable="true"/>
So in this way, I could fetch values for the keys defined in the spring config file, just like how we get the values from property files.
Thanks,
Rahul

How to inject properties into a spring bean from Main class

I'm using spring with my application, and I'm able to inject some properties from some file on a class path into my app and everything works perfectly. i.e.
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
Now I can use ${any.property.from.application.properties} in my spring context. And in my main class :
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("appContext.xml");
It works as well, my question is how do I inject property file location in the spring context without it being there at first, I want to make my app configurable. If I'm executing my app from C:\dir or /user/home/dir I assume that in the application context the value should be either C:\application.properties or /user/home/dir/application.properties
I had a similar problem sometime back. My requirement was the the property files is not bundled inside the application (and hence not in classpath). The file could be at any location in file system.
Here is how I solved it,
Define an environment variable the value of which points to the location of application.properties.
Lets say we have a env variable APP_PROP_HOME with value /user/home/dir/
Now while defining ServletContextPropertyPlaceholderConfigurer, define the locations as follows
I am reusing your example
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>file://${APP_PROP_HOME}/application.properties</value>
</list>
</property>
</bean>
The Spring resolves ${APP_PROP_HOME} to the value stored in corresponding env property and your application is configured at runtime.
If I am reading your question correctly, You want to use an external properties file(i.e File is not in the application runtime class path). If that is the case you need to use the file tag
<value>file:///c:\application.properties</value>
You can use #Value to inject values from the env. Example:
private someFoo;
#Value("${systemProperties.someFoo}")
public void setSomeParam(String someParam) {
this.someFoo = someParam;
}

how to read System environment variable in Spring applicationContext

How to read the system environment variable in the application context?
I want something like :
<util:properties id="dbProperties"
location="classpath:config_DEV/db.properties" />
or
<util:properties id="dbProperties"
location="classpath:config_QA/db.properties" />
depending on the environement.
Can I have something like this in my application Context?
<util:properties id="dbProperties"
location="classpath:config_${systemProperties.env}/db.properties" />
where the actual val is set based on the SYSTEM ENVIRONMENT VARIABLE
I'm using Spring 3.0
You are close :o)
Spring 3.0 adds Spring Expression Language.
You can use
<util:properties id="dbProperties"
location="classpath:config_#{systemProperties['env']}/db.properties" />
Combined with java ... -Denv=QA should solve your problem.
Note also a comment by #yiling:
In order to access system environment variable, that is OS level
variables as amoe commented, we can simply use "systemEnvironment"
instead of "systemProperties" in that EL. Like
#{systemEnvironment['ENV_VARIABLE_NAME']}
Nowadays you can put
#Autowired
private Environment environment;
in your #Component, #Bean, etc., and then access the properties through the Environment class:
environment.getProperty("myProp");
For a single property in a #Bean
#Value("${my.another.property:123}") // value after ':' is the default
Integer property;
Another way are the handy #ConfigurationProperties beans:
#ConfigurationProperties(prefix="my.properties.prefix")
public class MyProperties {
// value from my.properties.prefix.myProperty will be bound to this variable
String myProperty;
// and this will even throw a startup exception if the property is not found
#javax.validation.constraints.NotNull
String myRequiredProperty;
//getters
}
#Component
public class MyOtherBean {
#Autowired
MyProperties myProperties;
}
Note: Just remember to restart eclipse after setting a new environment variable
Check this article. It gives you several ways to do this, via the PropertyPlaceholderConfigurer which supports external properties (via the systemPropertiesMode property).
Yes, you can do <property name="defaultLocale" value="#{ systemProperties['user.region']}"/> for instance.
The variable systemProperties is predefined, see 6.4.1 XML based configuration.
In your bean definition, make sure to include "searchSystemEnvironment" and set it to "true". And if you're using it to build a path to a file, specify it as a file:/// url.
So for example, if you have a config file located in
/testapp/config/my.app.config.properties
then set an environment variable like so:
MY_ENV_VAR_PATH=/testapp/config
and your app can load the file using a bean definition like this:
e.g.
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>file:///${MY_ENV_VAR_PATH}/my.app.config.properties</value>
</list>
</property>
</bean>
Using Spring EL you can eis example write as follows
<bean id="myBean" class="path.to.my.BeanClass">
<!-- can be overridden with -Dtest.target.host=http://whatever.com -->
<constructor-arg value="#{systemProperties['test.target.host'] ?: 'http://localhost:18888'}"/>
</bean>
For my use case, I needed to access just the system properties, but provide default values in case they are undefined.
This is how you do it:
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="myBean" class="path.to.my.BeanClass">
<!-- can be overridden with -Dtest.target.host=http://whatever.com -->
<constructor-arg value="${test.target.host:http://localhost:18888}"/>
</bean>
Declare the property place holder as follows
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="locations">
<list>
<value>file:///path.to.your.app.config.properties</value>
</list>
</property>
</bean>
Then lets say you want to read System.property("java.io.tmpdir") for your Tomcat bean or any bean then add following in your properties file:
tomcat.tmp.dir=${java.io.tmpdir}
This is how you do it:
<bean id="systemPrereqs" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" scope="prototype">
<property name="targetObject" value="#{#systemProperties}" />
<property name="targetMethod" value="putAll" />
<property name="arguments">
<util:properties>
<prop key="deployment.env">dev</prop>
</util:properties>
</property>
</bean>
But remember spring gets loaded first and then it will load this bean MethodInvokingFactoryBean. So if you are trying to use this for your test case then make sure that you use depends-on. For e.g. in this case
In case you are using it for your main class better to set this property using your pom.xml as
<systemProperty>
<name>deployment.env</name>
<value>dev</value>
</systemProperty>
You can mention your variable attributes in a property file and define environment specific property files like local.properties, production.propertied etc.
Now based on the environment, one of these property file can be read in one the listeners invoked at startup, like the ServletContextListener.
The property file will contain the the environment specific values for various keys.
Sample "local.propeties"
db.logsDataSource.url=jdbc:mysql://localhost:3306/logs
db.logsDataSource.username=root
db.logsDataSource.password=root
db.dataSource.url=jdbc:mysql://localhost:3306/main
db.dataSource.username=root
db.dataSource.password=root
Sample "production.properties"
db.logsDataSource.url=jdbc:mariadb://111.111.111.111:3306/logs
db.logsDataSource.username=admin
db.logsDataSource.password=xyzqer
db.dataSource.url=jdbc:mysql://111.111.111.111:3306/carsinfo
db.dataSource.username=admin
db.dataSource.password=safasf#mn
For using these properties file, you can make use of REsource as mentioned below
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("classpath:"+System.getenv("SERVER_TYPE")+"DB.properties");
configurer.setLocation(resource);
configurer.postProcessBeanFactory(beanFactory);
SERVER_TYPE can be defined as the environment variable with appropriate values for local and production environment.
With these changes the appplicationContext.xml will have the following changes
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${db.dataSource.url}" />
<property name="username" value="${db.dataSource.username}" />
<property name="password" value="${db.dataSource.password}" />
Hope this helps .
Thanks to #Yiling. That was a hint.
<bean id="propertyConfigurer"
class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
<property name="locations">
<list>
<value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value>
</list>
</property>
</bean>
After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your terminal/IDE after creating that environment variable.
Updated version (2020).
Use System.getenv("ENV_VARIABLE")

property-placeholder location from another property

I need to load some properties into a Spring context from a location that I don't know until the program runs.
So I thought that if I had a PropertyPlaceholderConfigurer with no locations it would read in my.location from the system properties and then I could use that location in a context:property-placeholder
Like this
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>
<context:property-placeholder location="${my.location}"/>
but this doesn't work and nor does location="classpath:${my.location}"
Paul
You can do this with a slightly different approach. Here is how we configure it. I load default properties and then overrided them with properties from a configurable location. This works very well for me.
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="locations">
<list>
<value>classpath:site/properties/default/placeholder.properties
</value>
<value>classpath:site/properties/${env.name}/placeholder.properties
</value>
</list>
</property>
</bean>
The problem here is that you're trying to configure a property place holder using property placeholder syntax :) It's a bit of a chicken-and-egg situation - spring can't resolve your ${my.location} placeholder until it's configured the property-placeholder.
This isn't satisfactory, but you could bodge it by using more explicit syntax:
<bean class="org.springframework.beans.factory.config.PropertyPlaceHolderConfigurer">
<property name="location">
<bean class="java.lang.System" factory-method="getenv">
<constructor-arg value="my.location"/>
</bean>
</property>
</bean>

Categories