fbpx
Pages Navigation Menu

Coding is much easier than you think

Bean Method invocation using spEL

Bean Method invocation  using spEL

 


 

Step 1 : Create the POJO

 
File : Customer.java
 

package com.simpleCodeStuffs.spEL;

public class Customer {

	private String name;
	private double bill;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getBill() {
		return bill;
	}

	public void setBill(double bill) {
		this.bill = bill;
	}
}

 

File : Amount.java
 

package com.simpleCodeStuffs.spEL;

public class Amount {

	public double billAmount() {
		return 100.9;
	}
}

 
The scenario is such that the value of bill€™ attribute of ‘Customer’€™ depends on the value returned from ‘billAmount()’ method of ‘Amount’
 

Step 2 : Create the xml file

 

File : elBeans.xml
 

<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-3.0.xsd">

	<bean id="cust" class="com.simpleCodeStuffs.spEL.Customer">
		<property name="name" value="#{'SANDY'.toLowerCase()}" />
		<property name="bill" value="#{amount.billAmount()}" />
	</bean>
	<bean id="amount" class="com.simpleCodeStuffs.spEL.Amount">
	</bean>
</beans>

 
Note here, method invocation is done on Amount class through the bean as

spEL #{amount.billAmount()} and the returned value is set to bill using injection.

 

Step 3 : Create the main class

 
File : MainClass.java

package com.simpleCodeStuffs.spEL;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {

		ApplicationContext context =
         		new ClassPathXmlApplicationContext("elBeans.xml");
		Amount bill = (Amount) context.getBean("amount");
		Customer customer = (Customer) context.getBean("cust");

		System.out.println("Customer name: " + customer.getName());
		System.out.println("Bill amount: " + customer.getBill());
	}

}

 

Step 4 :

 
The output is

spelMethodInvocOutput

 

 

About Mohaideen Jamil


I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Advertisements
%d bloggers like this: