Referencing a value from a spring config - java

First a bit of setup info:
I have a multi-tenant spring based application. The multi-tenant enabling library is an in-house developed tool where I work that I have to use. How it works is that there is an interceptor that sets in front of the servlet for the application. Upon a request hitting the servlet it loads a tenant specific spring config for "stuff" needed for the tenant specified on the url hitting the servlet.
As stated, the above is just a bit of background. Now to the issue/question:
What I want to do is to create, in the tenant configuration that is loaded, a value that I can use to inject where I need. So, is there a way I can just define a constant in a spring config and then reference it via #Value or #Resource in java code?
There will be no bean implementation behind it, it would just be purely and only a key/value that I can reference where needed in my application by name. So, something to the effect of:
<bean name="MyIdentifier">
<property name="theId" value="1001" />
</bean>
And then can I do something like?
#Value{MyIdentifier.theId}
String theId;
And have Spring be aware of and inject the value. The problem is that doing something like above Spring complains there is no implementation for the bean. Notice, no class specified for the bean. The reason I want to do this is every tenant config file will contain this bean, but the actual value will vary per tenant.
Is there some other type to use in the config to do this? If so, what schemas have to be on the config?
I am guessing I am either trying to make Spring do something not intended, or, this is so simple I cannot see it since I have stared at it too long. Anyway, thanks for the help.

You can not create bean tag in configuration file without providing class implementation. If you want to inject the value of fields, you have to go for properties file instead.
Create property file as below:
application.properties
theId=1001
Load property file in your configuration:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
And access the property in your concrete class:
#Value("${theId}")
String theId;

Related

Spring Boot Configuration Priority

I am working on a new project and using Spring-Boot for the first time.
Traditionally, when using Spring and property files for configuration, I provided default properties in the distribution (WAR) and allowed for overriding them in some documented place.
For example:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:app.properties</value>
<value>file:${user.home}/.company/app/app.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="ignoreResourceNotFound" value="true" />
</bean>
This would allow us to re-deploy the application without losing local system configurations.
After reading the documentation on this for Spring-Boot, it seems that anything in "application.properties" takes a higher priority, and overwrites, anything specified with the #PropertySource annotation.
I like Spring because it allows us to stick to convention, which concerns me that I may have been doing the properties cascading wrong.
What would be the most appropriate way to provide externalized properties, with sensible defaults (embedded database, simple authentication, etc) that are included in the distribution?
Also, if anyone knows, I would love to know the reasoning behind the order for properties in Spring-Boot.
Note
I've tried looking at SpringApplication.setDefaultProperties, but cannot seem to find where to get a reference to the SpringApplication Object. The main method calls a static method on it (run), which is never actually run when bundled as a WAR file. It also seems a little bit of a hack to do it this way.
SpringApplication is a public class so you can create an instance and set its properties before running your app (the static run() methods are just conveniences). You can also use SpringApplicationBuilder, which is what you get as a callback when you are running in an external container anyway. Using those APIs you can set default properties, and profiles, including the location (spring.config.location) and name (spring.config.name) of the application.properties file.
Note that (per the link you provided) you can also use JNDI variables in the container to override or set environment properties. That could also be useful if you are packing multiple apps into the same JVM.

Can a Spring Batch job bean be lazily initialized?

In Spring, beans can be configured to be lazily initialized. Spring Batch jobs are also (Spring-managed) beans. That is, when I configure something like
<sb:job id="dummyJob" job-repository="jobRepository">
<sb:step id="dummyStep">
<sb:tasklet ref="dummyTasklet" />
</sb:step>
</sb:job>
I actually configure a new (Job-typed) bean inside the Spring container.
My issue is I really want my Job beans to be lazily initialized. As they are regular Spring-managed beans, I'd expect I can instruct the Spring context to make them lazy. This is because I have a large number of beans and there are many cases in which, during one execution of my Spring-based application, I only run one job.
But there's no lazy-init property I can set on my <sb:job... \> configuration. Is there any way I can force lazy initialization? If I configure my <beans\> root with default-lazy-init="true", will this also apply to the Job beans?
You have two options here:
Configure your job manually. This would allow you to use the regular lazy-init attributes Spring exposes.
Use the JobScope now available in Spring Batch 3. Spring Batch 3 will be available soon, but the JobScope was available in the last milestone.
Just to elaborate on Michael Minella's answer.
I had a similar requirement to lazy initialize the job repository.
I am working with Spring Batch 2.1.9.
The following is working for me.
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"
lazy-init="true">
<property name="dataSource" ref="jobDataSource"/>
<property name="transactionManager" ref="jobTransactionManager"/>
</bean>
Note one pitfall I had run into: do not set the databaseType i.e. avoid the following:
<property name="databaseType" value="SQLSERVER"/>
This is bad because it disable the auto-discovery of the database type and breaked my JUnits that works on H2.

working with JTATransactionManager in spring?

I am trying to use JtaTransactionManager in spring/hibernate. I have below configuration.
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="userTransactionName" value="java:comp/UserTransaction"></property>
</bean>
Now can i mark my service methods with #Transactional ? or do i need any extra configuration to use #Transactional ? do i need to add ?
An annotation is nothing more then metadata, so only slapping an annotation on there and expect it to magically work isn't going to happen.
To make #Transactional work you need to tell spring that you want to use annotation to drive your transactions. For this add the <tx:annotation-driven /> tag to your configuration.
However that probably isn't going to be all there is needed as you also need to configure hibernate appropriately for JTA.
A small tip instead of defining the bean, use the shorter <tx:jta-transaction-manager />. This will do some detection on which app server you are running and configure the appropriate transaction manager for you. See http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html#transaction-application-server-integration for more information.

Spring lazy initialization in development environment

In order to reduce the server startup time in development envrionment, I would like to change the default behaviour of Spring to lazily initialize the beans.
I know this can be done by specifying default-lazy-init="true" at the beans level. However I would not want to change this property everytime I get the latest config files from SCM and change it back before checking it back in.
Is there any other way out to externalize this property? Like specifying a System property?
I also tried to define a property in an environment specific property file and refer to the property in beans element, but it did not work.
default-lazy-init="${default-lazy-init-value}"
Any other way this can be achieved easily?
How about taking default-lazy-init in an external properties file and passing it to the bean definition
XML
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:system-env.properties</value>
</list>
</property>
</bean>
<bean id="bean1" class="com.Foo" lazy="${default-lazy-init}"/>
Properties File (system-env.properties)
#set true in dev (if needed)
default-lazy-init=true
You could use the following:
<beans default-lazy-init="true">
<!-- no beans will be pre-instantiated... -->
</beans>
...as described on http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-lazy-init

WebSphere and PropertyPlaceholderConfigurer

I'm a big user of properties (with PropertyPlaceholderConfigurer) for making my application as "dynamic" as possible. Almost all the constants are defined as such. Anyway, I'm currently defining a default.properties which comes shipped with the default WAR.
In other environments (Acceptance/Production) I need to overwrite of the configurations. I'm doing this as following:
<bean id="propertyManager"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:com/company/default.properties</value>
<value>file:${COMPANY_PROPERTIES_LOCATION}\kbo-select-settings.properties</value>
</list>
</property>
</bean>
With this means I can use a promotable build for each of the environments.
HOWEVER, I do dislike the fact that I can't change any of my properties from inside WebSphere. Instead I have to go to each of the servers (we have 8 clustered) and change the properties accordingly. It would be a lot more user friendly if I could change those from inside WebSphere and just perform a restart afterwards...
Anyone has an idea on how I could do such a promotable build? I already define JNDI configuration for datasources/java mail/etc.
Thanks!
We solved this problem by using an extension on the property file for each environment (local, dev, int, tst ...) and each file contained specific values for those environments. The only addition you then require is a VM argument on the server to set -Druntime.env=X.
Your lookups in your config file will then look like this
<bean id="propertyManager"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:com/company/default.properties.${runtime.env}</value>
<value>file:${COMPANY_PROPERTIES_LOCATION}\kbo-select-settings.properties</value>
</list>
</property>
</bean>
Of course this only works if you have fairly static environments, as it still doesn't lend itself to changing it at runtime, but it does makes promotion of the application dead simple. If you want to be able to change the values without redeploying your application, you will have to have them stored outside your application, which you already seem to be doing for the kbo-select-settings.properties
One potential issue is that you are hardcoding the location of your properties file. You could specify the location of the properties file as a JNDI resource and falling back on the defaults specified on the classpath:
<!-- try to lookup the configuration from a URL, if that doesn't work, fall back to the properties on the classpath -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<bean class="org.springframework.core.io.UrlResource">
<constructor-arg>
<jee:jndi-lookup
jndi-name="url/config"
default-value="file:///tmp" /> <!-- dummy default value ensures that the URL lookup doesn't fall over if the JNDI resource isn't defined -->
</constructor-arg>
</bean>
</property>
<property name="properties">
<bean class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:com/company/default.properties</value>
</list>
</property>
</bean>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
That way you can specify different file names for different environments using the WAS console in Resources > URL > URLs by creating a resource with the JNDI-name "url/config" and pointing it to the correct file (file:///your/path/to/properties).
As an alternative solution, if you want to manage individual properties through the console, you instead of using the PropertyPlaceholderConfigurer you could use jee:jndi-lookup to get values from the web.xml env-entries (which you can manage using the WAS console). See this answer
If the configuration is in the EAR file then I know of no simple way to propogate changes without backdoor cheats or re-deploying the app.
I think that configuration, espcially that which changes when you promote the app should not be in the application.
One approach is described here by Keys Botzum,
Note that you can actually propogate files that are not part of any particular application out to nodes using standard WebSphere synchronisation.
Another option is to use a database for config. These days poppin XML into a DB such as DB2 is not very hard.
Adding a URL resource that points to your config files to your websphere servers and then looking that up in your application is a viable way to go. You can then configure the url to point to a central location where all the configuration files are managed - if you use svn and your svn has read-only access you could even directly read them from svn (via http).
Spring has some built in facilities for this, and it also means you can priorities various config files.
For more information take a look at how-to-differentiate-between-test-and-production-properties-in-an-application
The way that I have dealt with this is to use property values on the JVM's but then reference them to a WebSphere variable that is defined at the cluser or cell level. For example, say you want a value called value1 set in param1 in your spring configuration you would do the following:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" />
And then something like as follows do reference the variable:
<bean id="id" class="com.blah.class">
<property name="value1" value="${param1}" />
</bean>
Then within your tests you can setup your tests as follows:
/**
* #see org.springframework.test.AbstractSingleSpringContextTests#prepareApplicationContext(org.springframework.context.support.GenericApplicationContext)
*/
#Override
protected void prepareApplicationContext(GenericApplicationContext context) {
System.setProperty("param1", "myvalue");
}
Then from within the websphere configuration, if you create a JVM variable and link it to the WebSphere variable you only need to change the WebSphere variable and it will automatically update all the JVM variables on each machine.
To do this, create a JVM variable called:
param1
with a value of ${webspherevar.param1}
And then create a WebSphere variable called:
webspherevar.param1
That contains whatever the value you need to put in it. This allows you to then not have to ship around the values for each environment and they can be instead loaded into the environment and just used.
I hope this helps.

Categories