Custom function for Spring ApplicationContext - java

I'm heavily using Spring to develop an application and I was wondering if there's a way to register custom method which can be used when a bean is defined. Currently I'm using ClassPathXmlApplicationContext to load the bean definitions from a XLM file, then in the XML file I would like to do something like
<bean id="bean1" class="..." scope="prototype"
p:some_property='"hello" + #getCorrelativeNumber()/>
Here some_property should then be evaluated to hello0. I know I can register custom functions using StandardEvaluationContext of SpEL, however I can't figure how to make that work in the context of the ApplicationContext.
Any help is greatly appreciated.

Please refer to this blog, look at the section which shows to create an application context in which expressions are used to inject values
<bean id="engine" class="com.baeldung.spring.spel.Engine">
<property name="capacity" value="3200"/>
<property name="horsePower" value="250"/>
<property name="numberOfCylinders" value="6"/>
</bean>
<bean id="someCar" class="com.baeldung.spring.spel.Car">
<property name="make" value="Some make"/>
<property name="model" value="Some model"/>
<property name="engine" value="#{engine}"/>
<property name="horsePower" value="#{engine.horsePower}"/>
</bean>

Related

Java Spring IOC bean creation value

I need a bean like this
<bean id="studentWithSchool" class="com.model.Student" scope="prototype">
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
</bean>
This is OK.
My problem is I have the student returning from a method from a different bean.
I usually load the bean like this when is a property.
<property name='beanProperty' value='#{anotherBean.getBeanProperty()}'/>
But in this case I need the new bean itself being set from the other bean method (School object is returned from another bean method).
This is what I try, and of course this is wrong:
<bean id="studentWithSchool" class="com.model.Student" scope="prototype" value='#{anotherBean.getBeanProperty()}'>
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
</bean>
Is there any workaround?
If I understand you correctly, the studentWithSchool is created and returned by a method in anotherBean. If that's the case, you can use a factory-method:
<bean id="studentWithSchool" factory-bean="anotherBean" factory-method="getBeanProperty" scope="prototype" />
I believe you are trying to use factory patter with Spring . For that you can use factory bean from spring.
<bean id="studentWithSchool" factory-bean="anotherBeanStaticFactory" factory- method="createBeanProperty" scope="prototype"
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
For more detail you can use below link :-
http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/beans/factory/BeanFactory.html

How to stick with both XML and Annotation based configuration Spring

Currently i am using spring 2.5 XML based configuration for bean. Now i want to upgrade it to Spring 3.x. I want to know after upgrading to 3.x my old XML configuration will work or not. If works then can i write annotation based configuration for new work in my current project.
Example of XML configuration:
<bean id="addTestimonialController" class="com.eam.web.testimonial.AddTestimonialController" singleton="true">
<property name="branchManager" ref="branchMan"/>
<property name="userManager" ref="userMan"/>
<property name="itemManager" ref="itemMan"/>
<property name="vendorManager" ref="vendorMan"/>
<property name="categoryManager" ref="categoryMan"/>
<property name="lineupManager" ref="lineupMan"/>
<property name="testimonialManager" ref="testimonialMan"/>
<property name="categoryMenuManager" ref="categoryMenuMan"/>
<property name="setManager" ref="setMan"/>
<property name="configurationManager" ref="configMan"/>
<property name="cartManager" ref="cartMan"/>
<property name="employeeManager" ref="employeeMan"/>
<property name="employeeBranchManager" ref="employeeBranchMan"/>
<property name="orderItemManager" ref="orderItemMan"/>
<property name="orderFaxManager" ref="orderFaxMan"/>
<property name="sessionForm" value="true"/>
<property name="commandName" value="addTestimonialBean"/>
<property name="branchesVendorManager" ref="branchesVendorMan" />
<property name="commandClass" value="com.eam.bus.testimonial.TestimonialBean"/>
<property name="validator" ref="addTestimonialValidator"/>
<property name="formView" value="addtestimonial"/>
<property name="successView" value="listtestimonials.html"/>
</bean>
Please help me. Also let me know if you similar link where somebody has explained both the configuration in a single configuration file.
Appreciate your help.
You can very well use both XML based metadata and Annotation based configuration metadata in your application. The configuration metadata is the information how you tell the Spring container to instantiate, configure, and assemble the objects in your application. Configuration metadata is traditionally supplied in a simple and intuitive XML format. i.e XML based configuration metadata. Spring 2.5 introduced support for annotation-based configuration metadata.Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus, you have different ways of providing your configuration metadata of your application through XML, Annotation based and Java config from Spring 3.x versions. This link will take you in the right direction. You must have to learn IOC chapter in Spring documentation
you can use both annotation based configuration and xml based (ControllerClassNameHandlerMapping ) by specifying the order of these handlers.
for annotation based Configuration use below
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >
<property name="order" value="0"/>
</bean>
for annotation based configuration we have to provide location ie: where to locate annotated controllers.
<context:component-scan base-package="ur packageName" />
here package name will be the package where #Controller classes are located.
for Controller Class Name based url Mapping
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name= "order" value="2"/>
</bean>

Compound beans in Spring?

Suppose I have my own bean which contains another beans hardcoded.
How to join this with Spring configuration?
First way is to use factory-method:
<bean id="bean1" class="myClass1"/>
<bean id="bean1.member" factory-bean="bean1" factory-method="getMember"/>
<bean id="bean2" class="myClass2">
<property name="collaborator" ref="bean1.member"/>
</bean>
Another way is to use EL:
<bean id="bean1" class="myClass1"/>
<bean id="bean2" class="myClass2">
<property name="collaborator" value="#{bean1.member}"/>
</bean>
In latter case Spring does not realize the dependency. Anyway, Bean Graph in Eclipse displays beans unrelated.
Are there better ways? May be I may implement some interface with MyClass1 so that it will treated as container or context?
You should create a separate bean for bean1.member and inject it into bean1
<bean id="bean3previouslyMember" class="myCompoundBean"/>
<bean id="bean1" class="myClass1">
<property name="member" ref="bean3previouslyMember"/>
</bean>
<bean id="bean2" class="myClass2">
<property name="collaborator" ref="bean3previouslyMember"/>
</bean>
Unless myClass1 is not modifiable and has no setter, this is generally what we do.

spring dynamic domain in HttpInvokerProxyFactoryBean

I'm new to spring and its bean injection framework and I need advice on understanding how to utilize them. Currently I have the following,
<beans>
<bean id="citationService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="http://localhost:8080/PPDFWeb/hello.htm"/>
<property name="serviceInterface" value="test_client.HelloService"/>
<property name="httpInvokerRequestExecutor">
<bean class="org.springframework.security.remoting.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor">
</bean>
</property>
</bean>
</beans>
Now i need the domain name of the service url to be dynamic so I can set it somewhere programmatically in my code. Is there some way to leave the bean intact in the xml and change the serviceUrl of the bean?
Just mark it like:
<property name="serviceUrl" value="{serviceURL}"/>
Edit:
There are just too many solutions available on SO, I didn't do a good search earlier:
reading a dynamic property list into a spring managed bean
HttpInvokerProxyFactoryBean-set-url-dynamically

constructor-arg and property together in bean definition

<bean id="cObject" scope="request" class="x.y.z.CClass"/>
<bean id="bObject" scope="request" class="x.y.z.BClass"/>
<bean id="aObject" scope="request" class="x.y.z.AClass">
<constructor-arg ref="bObject" />
<property name="cRef" ref="cObject" />
</bean>
aObject.cRef is not getting set for some reason. Note that constructor-arg and property are used in the same definition. I have not seen an example / post with similar feature.
On same sources my colleague discover:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'service.MenuService#0'
defined in class path resource [spring-beans/integrator.xml]:
Could not resolve matching constructor (hint: specify index/type/name
arguments for simple parameters to avoid type ambiguities)
while my host, test and production servers have no such error.
With:
<bean class="service.MenuService">
<constructor-arg index="0" type="java.lang.String" value="#{user}"/>
<constructor-arg index="1" type="java.lang.String" value="#{password}"/>
<constructor-arg index="2" type="java.lang.String" value="#{uri}"/>
<property name="system" value="OPRT"/>
<property name="client" value="OPRT"/>
</bean>
while there are only one 3-args constructor in bean.
The reason to use constructor - it perform some additional actions on non-Spring library by invoking init() method. And set args as fields.
So I change spring-beans.xml to:
<bean class="service.MenuService" init-method="init">
<property name="login" value="#{user}"/>
<property name="password" value="#{password}"/>
<property name="httpsUrl" value="#{uri}"/>
<property name="system" value="OPRT" />
<property name="client" value="OPRT" />
</bean>
Take attention to init-method= part.
UPDATE After all I wrote simple XML config and step through Spring source code in debugger. Seems that with Spring 3.x it's possible to combine constructor-arg and property in XML bean definition (check doCreateBean in AbstractAutowireCapableBeanFactory.java, which call createBeanInstance and populateBean next).
See also https://softwareengineering.stackexchange.com/questions/149378/both-constructor-and-setter-injection-together-in-spring/
Mixing <constructor-arg> and <property> is generally a bad idea.
There is only one good reason for using <constructor-arg>, and that is to create immutable objects.
However, your objects are not immutable if you can set their properties. Don't use <constructor-arg>. Redesign the class, use an initializer method annotated with #PostConstruct if you need to apply some logic at bean creation time.

Categories