Change spring bean alias with System property - java

I try to figure out whether it's possible to change a spring alias configuration through a system property.
That's the configuration:
<beans>
<bean id="beanOne" ... />
<bean id="beanTwo" ... />
<bean id="beanThree" ... />
<alias name="beanOne" alias="beanToUse" />
<bean id="consumer" ...>
<constructor-arg ref="beanToUse" />
</bean>
</beans>
I'd like to be able to use a JVM property e.g. with -Duse=beanThree to select another bean for the alias.
Unfortunately using the straight forward solution <alias name="#{systemProperties.use}" alias="beanToUse" /> throws a NoSuchBeanDefinitionException exception :(
Any suggestions?

Did you try to use spring 3.1 profiles?
<beans>
<bean id="beanOne" ... />
<bean id="beanTwo" ... />
<bean id="beanThree" ... />
<beans profile="A">
<alias name="beanOne" alias="beanToUse" />
</beans>
<beans profile="B">
<alias name="beanTwo" alias="beanToUse" />
</beans>
<bean id="consumer" ...>
<constructor-arg ref="beanToUse" />
</bean>
</beans>
and choose through system property -Dspring.profiles.active=A. I haven't tried aliases in profiles but you could just have alternative beanToUse definitions in each profile:
<beans>
<beans profile="A">
<bean id="beanToUse" ... defined as beanOne ... />
</beans>
<beans profile="B">
<bean id="beanToUse" ... defined as beanTwo .../>
</beans>
<bean id="consumer" ...>
<constructor-arg ref="beanToUse" />
</bean>
</beans>

Here's another way to do this using SpEL.
I have two implementations of DataStrategy type with bean ids testDataStrategy and realDataStrategy
I can choose between the beans by setting the property 'data.strategy' in the Property file in my Java project.
<bean id="myBeanId" class="com.some.path.MyBeanClass" >
<property name="dataStrategy" value="# {'${data.strategy}'.equalsIgnoreCase('TEST_DATA') ? testDataStrategy : realDataStrategy}" />
</bean>

Related

Two beans with same name in different contexts

I have the following beans in my contexs:
<!-- Context 1 -->
<beans profile="ldap">
<bean id="activeDirectoryAuthProvider" class="com.production.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="${ldap.login.provider.domain}"/>
<constructor-arg value="${ldap.login.provider.url}" />
<property name="useAuthenticationRequestCredentials" value="true" />
<property name="convertSubErrorCodesToExceptions" value="true" />
</bean>
</beans>
<!-- Context 2 -->
<bean id="activeDirectoryAuthProvider" class="com.test.TestActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="${ldap.login.provider.domain}"/>
<constructor-arg value="${ldap.login.provider.url}" />
<property name="useAuthenticationRequestCredentials" value="true" />
<property name="convertSubErrorCodesToExceptions" value="true" />
</bean>
My goal is to use the first bean only for production version another one for test purposes.
Namely when I start test based on production context I expect that production bean would be replaced by test bean with needed configuration.
But unfortunately when I tried to create two beans with same name only production bean is created and another one is ignored. Another thing that I noticed that when I tried to change test bean name to: activeDirectoryAuthProvider1 then both beans are successfully created. Can anyone explain why it happen and suggest possible solution how it can be bypassed?
You need to use different contexts for development and production. In each context you define only the relevant bean (i.e. only 1 bean with a certain name). If you use maven you can put the test/development context under src/test/resources and the production context under src/main/resources
If you do not use maven there are other approaches. You can find an example here: http://mrhaki.blogspot.it/2009/02/use-spring-configurator-to-support.html
Take a look at Spring Profiles you can have one for test and one for prod.
<beans profile="test">
<!-- Context 1 -->
<bean id="activeDirectoryAuthProvider" class="com.production.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="${ldap.login.provider.domain}"/>
<constructor-arg value="${ldap.login.provider.url}" />
<property name="useAuthenticationRequestCredentials" value="true" />
<property name="convertSubErrorCodesToExceptions" value="true" />
</bean>
</beans>
<beans profile="prod">
<!-- Context 2 -->
<bean id="activeDirectoryAuthProvider" class="com.test.TestActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="${ldap.login.provider.domain}"/>
<constructor-arg value="${ldap.login.provider.url}" />
<property name="useAuthenticationRequestCredentials" value="true" />
<property name="convertSubErrorCodesToExceptions" value="true" />
</bean>
</beans>
You can set the active profile in a various ways. Check the docs.

How to inherit proxied object in XML bean configuration

I have an AOP proxy bean defined as follows:
<bean id="someService" class="..FactoryBean">
..
<property name="target">
<ref local="target" />
</property>
<property name="preInterceptors"><ref local="serviceInterceptors"/></property>
..
</bean>
a target bean:
<bean id="target" class=".." />
and a child to the target bean:
<bean parent="target">
<!-- set some properties -->
</bean>
I'd like to change the target bean to an anonymous bean, but maintain the child bean. The only problem is setting parent attribute of child bean to AOP proxy bean inherits from the factory bean and not the target bean. Is there a work around for this?
Not pretty, but it should work:
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="com.foo.bar.ExampleService" />
</property>
</bean>
<bean id="targetSource" factory-bean="proxy" factory-method="getTargetSource" />
<bean id="parent" factory-bean="targetSource" factory-method="getTarget" />
<bean parent="parent" />

ehcache.xml can't use the properties file property

I define a system.properties in my class path, then I do like this in spring configuration xml:
<context:property-placeholder location="classpath*:/system.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />
I aslo defind ehcache like this :
<cache:annotation-driven cache-manager="cacheManager" />
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:/ehcache.xml" />
<property name="shared" value="true" />
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheManager" />
</bean>
I define a properties in system.properties file :
system.project_name=myproject
ehcache.xml like this :
<diskStore path="e:/${system.project_name}/cache" />
I want use the system.project_name property to store the cache, but when I deploy my project, I find the Directory is:
that is say I could't use the properties even I define a PropertyPlaceholderConfigurer in Spring configuration xml file?

How to resolve Spring Batch Error?

I am trying to learn Spring batch for writing batch jobs in java. So i am using this tutorial.
Now the problem is after I have used all the jars, i started executing the project . This left me with a devious error :
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1e7b1e7b: defining beans [jobLauncher,jobRepository,transactionManager,wordsFWTasklet,numbersFWTasklet,taskletStep,fileWritingJob]; root of factory hierarchy
Sep 3, 2013 8:09:29 AM org.springframework.batch.core.launch.support.CommandLineJobRunner start
SEVERE: Job Terminated in error: Error creating bean with name 'fileWritingJob' defined in class path resource [fileWritingJob.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
Throwable occurred: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileWritingJob' defined in class path resource [fileWritingJob.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:478)
Caused by: java.lang.NullPointerException
at org.springframework.core.GenericTypeResolver.getTypeVariableMap(GenericTypeResolver.java:144)
at org.springframework.core.GenericTypeResolver.resolveReturnType(GenericTypeResolver.java:93)
In case, you want to know the code that i have used for my configuration xml, it's below :
fileWritingJob.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="applicationContext.xml"/>
<bean id="wordsFWTasklet" class="FileCreatorTasklet">
<property name="filePath" value="C:\\temp\\words.txt"/>
<property name="content" value="abcdefghijklmnopqrstuwxyz"/>
</bean>
<bean id="numbersFWTasklet" class="FileCreatorTasklet">
<property name="filePath" value="C:\\temp\\numbers.txt"/>
<property name="content" value="0123456789"/>
</bean>
<bean id="taskletStep" abstract="true"
class="org.springframework.batch.core.step.tasklet.TaskletStep">
<property name="jobRepository" ref="jobRepository"/>
</bean>
<bean id="fileWritingJob" class="org.springframework.batch.core.job.SimpleJob">
<property name="name" value="fileWritingJob" />
<property name="steps">
<list>
<bean parent="taskletStep">
<property name="tasklet" ref="wordsFWTasklet"/>
<property name="transactionManager" ref="transactionManager"/>
</bean>
<bean parent="taskletStep">
<property name="tasklet" ref="numbersFWTasklet"/>
<property name="transactionManager" ref="transactionManager"/>
</bean>
</list>
</property>
<property name="jobRepository" ref="jobRepository"/>
</bean>
</beans>
EDIT :
ApplicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository"/>
</bean>
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.SimpleJobRepository">
<constructor-arg>
<bean class="org.springframework.batch.core.repository.dao.MapJobInstanceDao"/>
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.batch.core.repository.dao.MapJobExecutionDao" />
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.batch.core.repository.dao.MapStepExecutionDao"/>
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.batch.core.repository.dao.MapExecutionContextDao"/>
</constructor-arg>
</bean>
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
</beans>
Can any one tell me what am i doing wrong here ?
Which versione of spring-batch are you using? With 2.2.1.RELEASE (and 3.2.3.RELEASE of Spring framework) this example works fine!
Libraries (from maven) are:
org.springframework
spring-core
spring-beans
spring-context
spring-batch-core
spring-batch-infrastructure

Spring ApplicationContext Beans-wiring

I have two ApplicationContexts for my project (very huge project).
One old xml with data
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-autowire="autodetect">
</beans>
now I need to add my other project applicatinContext to it or any other way so that none of the modules will be impacted
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="positionResponsesDAO"
class="com.xxx.modules.worklist.DAO.Impl.PositionResponsesDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="positionDAO"
class="com.xxx..modules.worklist.DAO.Impl.PositionDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="nextActionDAO"
class="com.xxx..modules.worklist.DAO.Impl.NextActionDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean>
....... few more
</bean>
<bean id="workOrderManager" class="com.xxx.modules.worklist.action.manager.impl.WorkOrderManagerImpl">
<property name="positionDO" ref="positionDO" />
<property name="moveWorkOrderDO" ref="moveWorkOrderDO" />
<property name="nextActionDO" ref="nextActionDO" />
<property name="positionDAO" ref="positionDAO" />
<property name="moveResponsesDAO" ref="moveResponsesDAO" />
<property name="moveWorkOrderDAO" ref="moveWorkOrderDAO" />
<property name="nextActionDAO" ref="nextActionDAO" />
<property name="positionResponsesDAO" ref="positionResponsesDAO" />
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
<property name="jdbcUrl" value="driverUrl" />
<property name="user" value="MCMGR" />
<property name="password" value="MC123" />
</bean>
</beans>
the first one has Auto-wiring enabled and this one has and needs manual wiring. How can i combined both of them to put into one xml or read two configurations.
I don't see why reading two or more application context files is difficult. The usual Spring idiom is to partition configuration according to layer. I typically have configuration for persistence, service, web, etc. If it's a web application, I just add all of them in using the ContextLoaderListener. You can specify as many configuration files as you need.
I would consider one huge configuration file a liability in the same way that I would look down on one huge class for everything. Decomposition is a computer science fundamental. I'd recommend partitioning your configuration.
Mixing annotation-based and XML-based configuration isn't a problem, either.
You'll only have an issue if the two configurations overlap. You'll have to remove one or the other for the conflicted beans.
You can use the <import/> tag. See http://forum.springsource.org/showthread.php?41811-Application-Context-and-include

Categories

Resources