Add precondition value to bean property - spring

In the applicationContext rules xml file, I have rules defined to validate fileds for web forms. eg. The webFormCanadaConditionalRule will be triggered on the province filed and the rule checks to if the selected value is 5714 for Canada. If it is Canada are other filed will get validated.
here is a working example.
<entry key="province">
<list>
<value>webFormCanadaConditionalRule</value>
</list>
</entry>
<bean id="webFormCanadaConditionalRule"
class="ca.gc.cic.gol.eapp.rules.custom.WebFormConditionalRule">
<property name="preConditionValue" value="5714"/>
<property name="ruleNames" >
<list>
<value>mandatory</value>
</list>
</property>
</bean>
What I am trying to accomplish is to have a precondition value that checks to make sure the selected value is not 5714.
Is there a way I can add a precondition value to bean property where I can use the !=... Here is what I have and this doesn't seem to work.
<bean id="webFormAddressNotCanadaConditionalRule"
class="ca.gc.cic.gol.eapp.rules.custom.WebFormConditionalRule">
<property name="preConditionValue" value="${!=5714}" />
<property name="ruleNames" >
<list>
<value>mandatory</value>
</list>
</property>
</bean>
Thanks a lot.

Related

Manipulation of Spring Bean property

I want to change a property of a bean. I want to change it only once for performance (better when reading from XML), not in every bean instance instantiation. What is the best way to do it in Spring?
For elaborating and giving a concrete example:
Below is the datasource bean declaration in databaseContext.xml.
I want to decrypt ${jdbc.password} whose value is ENC(....) with JASYPT.
I could not do it with Jaspt Spring integration since Jaspt not compliant yet with Spring5 and not with Jasypt Hibernate integration since using a different datasource other than Hibernate.
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1 from dual" />
<property name="dataSourceClassName" value="oracle.jdbc.pool.OracleDataSource" />
<property name="maximumPoolSize" value="10" />
<property name="idleTimeout" value="30000" />
<property name="dataSourceProperties">
<props>
<prop key="url">${jdbc.url}</prop>
<prop key="user">${jdbc.user}</prop>
<prop key="password">${jdbc.password}</prop>
</props>
</property>
</bean>
This helped me a lot:
Spring property placeholder decrypt resolved property
Just want to add some small correction and extra notes about some findings:
In the link above it is written "location", but it must be "locations" as written below, where it resides at applicationContext.xml
<bean class="com.dummy.util.EncryptationAwarePropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:database.properties</value>
<value>classpath*:hibernate.properties</value>
</list>
</property>
</bean>
"PropertyPlaceholderConfigurer" is deprecated. But it still works. If you try to use the newly proposed class "PropertySourcesPlaceholderConfigurer", it has a bug that it does not call "convertPropertyValue" method as noted here: https://github.com/spring-projects/spring-framework/issues/13568. A workaround noted by the way there.
public class EncryptationAwarePropertySourcesPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
#Override
protected String convertPropertyValue(String originalValue) {
if (originalValue != null && originalValue.startsWith("ENC(")) {
return decrypt(originalValue);
}
return originalValue;
}
.
.
}

Null value is returned from spring DI

I am trying to read property file ,but value returned is null.
<bean id="propertylist" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="places">
<list>
<value>file:/myfile/configuration/myproject.properties</value>
</list>
</property>
</bean>
<bean id="callManagement" class="com.callManagement" scope="session">
<property name="googlemapjs" value="${googlemap.js}"/>
</bean>
IF i replace ${googlemap.js} it with hardcode value . IT still gives null
NOTE::if i try to generate setter and getter using source>generate setter and getter it give "resource is not on the build path of java project".So i have to manually define setter and getters
<property name="locations">
<list>
<value>classpath*:*.properties.default</value>
<value>classpath*:${name of properties file}.properties
</value>
</list>
</property>
</bean>
And keep the properties file in src/main/config if you are using maven in your project

Spring static factory with factory-method and parameter

I have a problem transfering code to Spring applicationContext.xml
The source is:
File inFile = new File ("path/to/file/", "fileName.docx")
WordprocessingMLPackage wordMLPackage = Docx4J.load(inFile);
My not working solution is:
<bean id="inFile" class="java.io.File">
<constructor-arg value="path/to/file/" />
<constructor-arg value="fileName.docx" />
</bean>
<bean id="docx4j" class="org.docx4j.Docx4J" factory-method="load">
<constructor-arg ref="inFile" />
</bean>
<bean id="wordprocessingMLPackage" class="org.docx4j.openpackaging.packages.WordprocessingMLPackage" factory-bean="docx4j" />
What I'm getting out of the bean "wordprocessingMLPackage" is indeed an instance of the Class WordprocessingMLPackage, but it seems empty although the File I'm trying to load isn't (and yes, the path is doublechecked).
When trying
MainDocumentPart mdp = wordprocessingMLPackage.getMainDocumentPart();
List<Object> content = mdp.getContent();
I'm getting a NullPointerException because mdp is null!
Has anyone an idea... or even a solution?
============================================================
I found a solution especially for my problem.
Here is the source of Docx4j.load():
public static WordprocessingMLPackage load(File inFile) throws Docx4JException {
return WordprocessingMLPackage.load(inFile);
}
That means I can create an instance of WordprocessingMLPackage by its static self!
The code which is working:
<bean id="wordprocessingMLPackage" class="org.docx4j.openpackaging.packages.WordprocessingMLPackage" factory-method="load">
<constructor-arg ref="baseDocument" />
</bean>
So I found a lucky "workaround" for the original problem.
Since this question isn't urgent any more, I'm still interested in the correct solution, especially in a solution which allows injecting the WordprocessingMLPackage in other beans.
Thank you!
Here you need to make use of MethodInvokingFactoryBean as detailed below.
<bean id="beanId"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.docx4j.Docx4J" />
<property name="targetMethod" value="load"/>
<property name="arguments">
<list>
<ref bean="inFile" />
</list>
</property>
</bean>
In your code get hold of applicationContext instance and invoke the below LOC
WordprocessingMLPackage ml = (WordprocessingMLPackage) applicationContext.getBean("beanId");
Let know in comments if you face any issues.
As Bond - Java Bond stated this works:
<bean id="inFile" class="java.io.File">
<constructor-arg value="path/to/file/" />
<constructor-arg value="fileName.docx" />
</bean>
<bean id="beanId" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.docx4j.Docx4J" />
<property name="targetMethod" value="load"/>
<property name="arguments">
<list>
<ref bean="inFile" />
</list>
</property>
</bean>
You can now use the bean as
WordprocessingMLPackage ml = (WordprocessingMLPackage) applicationContext.getBean("beanId");
or you can inject the bean directly as
<bean id="service" class="app.service.Service">
<property name="wordprocessingMLPackage" ref="beanId" />
</bean>
Thank you!!!

Using a MethodInterceptor to wrap calls to protected method

I would like to use XML based Spring configuration to wrap calls to a protected method in a 3rd party class. I have wired up some spring classes from org.springframework.aop.support. It works for public methods, but it fails for protected ones:
<bean id="sampleAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="proxyTargetClass" value="true" />
<property name="beanNames">
<list>
<value>thrirdPartyBean</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>sampleAdvisor</value>
</list>
</property>
</bean>
<bean id="sampleMethodNamePointcut" class="org.springframework.aop.support.NameMatchMethodPointcut">
<property name="mappedNames">
<list>
<value>publicMethodThatWorks</value>
<value>protectedMethodThatDoesNotWork</value>
</list>
</property>
</bean>
<bean id="sampleAdvice" class="sample.MyMethodInterceptor" />
<bean id="sampleAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="pointcut" ref="sampleMethodNamePointcut" />
<property name="advice" ref="sampleAdvice" />
</bean>
How can I tweak this to work with protected methods ?
As the linked question/answer in the comments states, Springs AOP proxies can only apply to public methods.
With JDK proxies, this isn't possible because the proxy only has your target object's interface types so you can only interact with it through its public methods (remember that all methods declared in an interface are public).
With GGLIB proxies, because the proxy does have the target object's class type, you can interact with its protected methods. I would think for reasons of consistency between proxying mechanisms they would not allow it.

Is it possible to alias bean class names in Spring?

I have a string property which looks similar to the following example:
<property name="mappingData">
<list>
<bean class="com.company.product.longNamingStandard.migration.extractor.FieldMapping">
<property name="elementName" value="entitlement.user"/>
<property name="mapping" value="DocUsers"/>
</bean>
<bean class="com.company.product.longNamingStandard.migration.extractor.FieldMapping">
<property name="elementName" value="entitlement.contributor"/>
<property name="mapping" value="DocContributors"/>
</bean>
</list>
</property>
The long class name(s) effect readability & also create a refactoring overhead.
Is it possible to alias the class name and use a short name to declare the beans? Or is there an alternate best practice I'm missing?
Probably a bit late for you, but hopefully useful for others:
You can use parent beans to accomplish this.
First declare a parent bean as a template:
<bean id="FieldMapping" class="com.company.product.longNamingStandard.migration.extractor.FieldMapping"/>
Then use it elsewhere, using the parent attribute.
<property name="mappingData">
<list>
<bean parent="FieldMapping">
<property name="elementName" value="entitlement.user"/>
<property name="mapping" value="DocUsers"/>
</bean>
<bean parent="FieldMapping">
<property name="elementName" value="entitlement.contributor"/>
<property name="mapping" value="DocContributors"/>
</bean>
</list>
</property>
Please note my convention here is to use upper case id's here for the parent template beans.
each <bean/> comes with an attribute of name and id to help you reference those beans later in your configuration.
I would suggest using the id for declaring the bean.
your config could look like:
<bean id="fooBean" class="com.example.foo"/>
<bean id="barBean" class="com.example.bar"/>
<list>
<ref>fooBean</ref>
<ref>barBean</ref>
</list>
You may try to represent your mapping in some short form, and then convert it to the list of FieldMappings. For example, mappings from your snippet may be represented as a map.
As a theoretic exercise in Spring 3 you can do this with Spring Expression Language (if FieldMapping has the apropriate constructor):
<util:map id = "m">
<entry name = "entitlement.user" value = "DocUsers" />
<entry name = "entitlement.contributor" value = "DocContributors" />
</util:map>
...
<property name = "mappingData"
value = "#{m.![new com.company.product.longNamingStandard.migration.extractor.FieldMapping(key, value)]}" />
If this expression is too obscure, you may implement a FactoryBean to take a short form of your mapping data (for example, a map, as in this example) and return a configured list of FieldMappings:
<property name = "mappingData">
<bean class = "FieldMappingListFactoryBean">
<property name = "mappings">
<map>
<entry name = "entitlement.user" value = "DocUsers" />
<entry name = "entitlement.contributor" value = "DocContributors" />
</map>
</property>
</bean>
</property>
However, if your field mappings are some kind of reusable DSL, you may try to think about implementing a namespace extension.
I found a way to simulate an effect similar to a "import com.Foo;" in java code. The best option I could find was to use a PropertyPlaceholderConfigurer with local properties defined. Using your example, here's the configuration that you would put at the top of your spring config file to define a "class_FieldMapping" property:
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<description>Define properties equivalent to "import foo;" in java source</description>
<property name="properties">
<props>
<prop key="class_FieldMapping">com.company.product.longNamingStandard.migration.extractor.FieldMapping</prop>
</props>
</property>
</bean>
Then, you can use that property within your beans:
<property name="mappingData">
<list>
<bean class="${class_FieldMapping}">
...
</bean>
<bean class="${class_FieldMapping}">
...
</bean>
</list>
</property>
This has the benefit that use can also use it for things where you actually need the class name, and can't reference an instance of an object:
<util:constant static-field="${class_FieldMapping}.MYSTATICVAR" />
Why not declare those inner beans as separate top-level beans with their own names, and then reference them in the list ?
If I use PropertyPlaceholderConfigurer it leads to several exceptions in debug log. It works, but it seems it doesn't work on the first try.

Resources