Is there a better way to Configure Bean? - spring

Can the following Spring DI xml be improved? Below the xml is the programmatic approach of configuring the target bean.
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</list>
</property>
</bean>
ObjectMapper mapper = new
ObjectMapper();
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

XML is a really bad way of doing this. Yes, you can do this, but it's much easier to write a FactoryBean which configures your ObjectMapper:
public class MyObjectMapperFactoryBean extends AbstractFactoryBean<ObjectMapper> {
public Class<ObjectMapper> getObjectType() {
return ObjectMapper.class;
}
public ObjectMapper createInstance() {
// create and return ObjectMapper
}
}
and then in your XML:
<bean id="jacksonObjectMapper" class="x.y.MyObjectMapperFactoryBean" />

Still not totally ideal, but a little cleaner:
<bean id="objectMapperBuilder1" class="org.codehaus.jackson.map.ObjectMapper"/>
<bean id="objectMapperBuilder2" factory-bean="objectMapperBuilder1" factory-method="setSerializationInclusion">
<constructor-arg value="NON_NULL"/>
</bean>
<bean id="jsonWriter" factory-bean="objectMapperBuilder2" factory-method="writerWithDefaultPrettyPrinter" />
<!-- etc, etc -->
One downside is that you'll have unnecessary bean instances in memory. (I'm using this method, and I'll live with it until Spring decides to handle these). There are many threads here and on the Spring forums asking for support with fluent setters like the builder pattern used by Jackson, but until then you have to choose the lesser evil for you.

I agree with #skaffman's general approach of using a FactoryBean in place of the unavoidably convoluted Spring XML bean configuration to configure a Jackson ObjectMapper. Spring 3.2+ now provides such a FactoryBean out of the box. See JacksonObjectMapperFactoryBean / Jackson2ObjectMapperFactoryBean. Here's an example of the Spring XML to configure the ObjectMapper via the Spring FactoryBean -
<bean id="jacksonObjectMapper" factory-bean="&jacksonObjectMapperFactoryBean" factory-method="getObject"/>
<bean id="jacksonObjectMapperFactoryBean" class="org.springframework.http.converter.json.JacksonObjectMapperFactoryBean">
<property name="featuresToDisable">
<array>
<util:constant static-field="org.codehaus.jackson.map.SerializationConfig$Feature.WRITE_NULL_PROPERTIES"/>
</array>
</property>
</bean>
(Note the need to use &amp in the 'factory-bean' attribute to instruct Spring to use the factory method on the FactoryBean itself, rather than the bean it creates).

Related

How to get key value from properties file at runtime using spring

I want to get the changed key value from properties file at runtime.
test.properties file:
name = Hi
I have made Thread sleep with 5 sec and changed the key value as "Hello" but it is not getting changed.
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:test.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:test</value>
</list>
</property>
<property name="cacheSeconds" value="1" />
</bean>
<bean id="tempBean" name="tempBean1" class="org.sri.spring.temp.Temp"
lazy-init="false" scope="prototype">
<constructor-arg type="String" value="${name}" />
</bean>
The ${name} placeholder inside the XML configuration is resolved using the PropertySourcesPlaceholderConfigurer which, as you may notice, has nothing in common with your reloadable messageSource.
It wouldn't work either way because Spring instantiates the tempBean only once: on application startup, by passing the value of ${name} to the constructor. The bean itself is not aware of where the value came from (and in particular, it doesn't care if the properties file gets edited).
If you really think it's a good idea to do it†, you can inject the entire messageSource into your tempBean, and get the current value in each call, e.g.:
public class Temp {
#Autowired // or wired in XML, constructor, etc.
private MessageSource messages;
public String sayHello() {
return messages.getMessage("name", null, Locale.getDefault());
}
}
† injecting a configuration-related object makes testing more difficult and is arguably bad design (mixing concerns). Have a look at the Spring Cloud Config project as it's likely that this is how the future is going to look like.
I do not think that Spring will update already existing beans when the properties change.
Try to create a new bean (prototype scope)

How would I specify a bean reference as an argument-resolver, in Spring 3-1?

This is a syntax question about a Spring configuration (refer to spring-beans-3.1.xsd and spring-mvc-3.1.xsd).
I have a specific bean definition (id="SecurityRequestParametersArgumentResolver") that I want to register as a custom argument resolver. The xml fragment is:
<bean id="SecurityRequestParametersArgumentResolver"
class="xxx.security.web.SecurityRequestParametersArgumentResolver">
<property name="credentialsManager" ref="CredentialsManager" />
<property name="tokenService" ref="TokenService" />
</bean>
... AND I would like to use a bean reference. The following three lines don't obey the xsd-grammar ( what should be the correct tag declaration here? )
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean ref="SecurityRequestParametersArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
... All of the examples I have seen look like THIS, and thus are going after the default no-argument constructor
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="class="xxx.security.web.SecurityRequestParametersArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
Repeating the question, what should the Spring syntax be in order to use a bean reference as a custom argument resolver?
Thanks!
At least the constructor argument problem can be solved easily
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="class="xxx.security.web.SecurityRequestParametersArgumentResolver">
<constructor-arg value="123"/>
</bean>
</mvc:argument-resolvers>
</mvc:annotation-driven>
But I do not know any way to use a reference instead of a bean within <mvc:argument-resolvers>. But depending on what you want to do, there are several workarrounds.
Use a Bean Factory
Create a proxy class that implements the HandlerMethodArgumentResolver and forward every call to an other instance, then you can have your own SecurityRequestParametersArgumentResolver like a normal bean and register the Proxy in the <mvc:argument-resolvers> section.
Proxy:
class HandlerMethodArgumentResolverProxy
implements HandlerMethodArgumentResolver{
HandlerMethodArgumentResolver delegate;
publicHandlerMethodArgumentResolverProxy
(HandlerMethodArgumentResolver delegate){
this.delegate=delegate;
}
public boolean supportsParameter(MethodParameter parameter) {
this.delegate.supportsParameter(parameter);
}
//delegate for resolveArgument
}
config:
<bean id="securityRequestParametersArgumentResolver"
class="xxx.security.web.SecurityRequestParametersArgumentResolver">
...
</bean>
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class "HandlerMethodArgumentResolverProxy">
<constructor-arg
ref="securityRequestParametersArgumentResolver"/>
</bean>
</mvc:argument-resolvers>
</mvc:annotation-driven>

Can I turn off quartz scheduler with a property setting?

We disable the quartz scheduler locally by commenting out the scheduler factory bean in the jobs.xml file.
Is there a setting for doing something similar in the quartz.properties file?
If you use Spring Framework you can make subclass from org.springframework.scheduling.quartz.SchedulerFactoryBean and override afterPropertiesSet() method.
public class MySchedulerFactoryBean extends org.springframework.scheduling.quartz.SchedulerFactoryBean {
#Autowired
private #Value("${enable.quartz.tasks}") boolean enableQuartzTasks;
#Override
public void afterPropertiesSet() throws Exception {
if (enableQuartzTasks) {
super.afterPropertiesSet();
}
}
}
Then change declaration of factory in xml file and set "enable.quartz.tasks" property in properties file. That's all.
Of course, instead using #Autowired you can write and use setter method and add
<property name="enableQuartzTasks" value="${enable.quartz.tasks}"/>
to MySchedulerFactoryBean declaration in xml.
No. But the properties file doesn't start the scheduler.
The scheduler doesn't start until/unless some code invokes scheduler.start().
It seems that there is a property autoStartup in org.springframework.scheduling.quartz.SchedulerFactoryBean. So you can configure it in XML config like this:
<bean id="quartzFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="autoStartup" value="${cron.enabled}"/>
<property name="triggers">
<list>
<ref bean="someTriggerName"/>
</list>
</property>
</bean>
Thanks to https://chrisrng.svbtle.com/configure-spring-to-turn-quartz-scheduler-onoff
You can disable Quartz Scheduler if you use Spring Framework 3.1 for creating and starting it.
On my Spring configuration file I use the new profiles feature of Spring 3.1 in this way:
<beans profile="production,test">
<bean name="bookingIndexerJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.xxx.indexer.scheduler.job.BookingIndexerJob" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="10" />
</map>
</property>
</bean>
<bean id="indexerSchedulerTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="bookingIndexerJob" />
<property name="startDelay" value="1000" />
<property name="repeatInterval" value="5000" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="indexerSchedulerTrigger" />
</list>
</property>
<property name="dataSource" ref="ds_quartz-scheduler"></property>
<property name="configLocation" value="classpath:quartz.properties" />
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
</beans>
Only when I want to start the Scheduler (for example on the production environment), I set the spring.profiles.active system property, with the list of active profiles:
-Dspring.profiles.active="production"
More info here:
http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/
http://java.dzone.com/articles/spring-profiles-or-not
I personally like the answer from Demis Gallisto. If you can work with profiles, this would be my recommendation.
Nowadays people most likely prefer to work with Annotations, so as an addition to his answer.
#Configuration
#Profile({ "test", "prod" })
public class SchedulerConfig {
#Bean
// ... some beans to setup your scheduler
}
This will trigger the scheduler only when the profile test OR prod is active. So if you set an different profile, e.g. -Dspring.profiles.active=dev nothing will happen.
If for some reasons you cannot use the profile approach, e.g. overlap of profiles ...
The solution from miso.belica seems also to work.
Define a property. e.g. in application.properties: dailyRecalculationJob.cron.enabled=false and use it in your SchedulerConfig.
#Configuration
public class SchedulerConfig {
#Value("${dailyRecalculationJob.cron.enabled}")
private boolean dailyRecalculationJobCronEnabled;
#Bean
public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, Trigger trigger) throws
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setAutoStartup(dailyRecalculationJobCronEnabled);
// ...
return factory;
}
// ... the rest of your beans to setup your scheduler
}
I had similar issue: disable scheduler in test scope.
Here is part of my applicationContext.xml
<task:annotation-driven scheduler="myScheduler" />
<task:scheduler id="myScheduler" pool-size="10" />
And I've disabled scheduler using 'primary' attribute and Mockito. Here is my applicationContext-test.xml
<bean id="myScheduler" class="org.mockito.Mockito" factory-method="mock" primary="true">
<constructor-arg value="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler"/>
</bean>
Hope this help!
The simplest way I've found in a spring boot context for tests is to simply:
#MockBean
Scheduler scheduler;
This scala code works:
#Bean
def schedulerFactoryBean(): SchedulerFactoryBean = {
new SchedulerFactoryBean {
override def afterPropertiesSet(): Unit = {}
}
}

Reading valued from properties file at Runtime

I want to get specific value based on request from the property file.how to do that?
I have following spring configuration.i want to set the value for Exprops as per the request and get corresponding values from the properties file
<bean id="Prop" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:ErrorMessage.properties</value>
</property>
</bean>
<bean id="PropertiesBean" class="com.util.PropertiesUtil">
<property name="Exprops" value="${EXampleExceptiion}"></property>
</bean>
Use the PropertiesFactoryBean to inject the Properties in a Bean.
<bean id="myPropertiesBean"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:ErrorMessage.properties"/>
</bean>
This provides a Properties Object/Bean which can be injected under the name myPropertiesBean in any Bean (<property name="x" ref="myPropertiesBean"/>).
In addition Spring provides the util namespace (since Spring 2.5):
There you can write the PropertyFactoryBean definition a bit shorter:
<util:properties id="myPropertiesBean"
location="classpath:ErrorMessage.properties"/>
#see Spring Reference Chapter C.2.2.3.
All use the following for doing this programmatically
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);
<util:properties id="" location="location of prop file" />
this return java.util.Properties object

How do you acess a property of a bean for reading in a spring xml config file?

I want to do something like the following in spring:
<beans>
...
<bean id="bean1" ... />
<bean id="bean2">
<property name="propName" value="bean1.foo" />
...
I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.
What I understood:
You have a bean (bean1) with a
property called "foo"
You have another bean (bean2) with a
property named "propName", wich also
has to have the same "foo" that in
bean1.
why not doing this:
<beans>
...
<bean id="foo" class="foopackage.foo"/>
<bean id="bean1" class="foopackage.bean1">
<property name="foo" ref="foo"/>
</bean>
<bean id="bean2" class="foopackage.bean2">
<property name="propName" ref="foo"/>
</bean>
....
</beans>
Doing this, your bean2 is not coupled to bean1 like in your example. You can change bean1 and bean2 without affecting each other.
If you REALLY need to do the injection you proposed, you can use:
<util:property-path id="propName" path="bean1.foo"/>
You need to use PropertyPathFactoryBean:
<bean id="bean2" depends-on="bean1">
<property name="propName">
<bean class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetBeanName" value="bean1"/>
<property name="propertyPath" value="foo"/>
</bean>
</property>
</bean>
I think you have to inject bean1, then get foo manually because of a timing issue. When does the framework resolve the value of the target bean?
You could create a pointer bean and configure that.
class SpringRef {
private String targetProperty;
private Object targetBean;
//getters/setters
public Object getValue() {
//resolve the value of the targetProperty on targetBean.
}
}
Common-BeanUtils should be helpful.

Resources