Home  >  Spring Core

XML based Spring Expression Support for Defining Bean Definitions

October 05, 2013
In this page, we will learn how to use Spring Expression to support bean definitions. A Bean needs input and that input can be provided by spring expression also. We will show spring expression support by XML based configuration. In XML based Configuration, we will define a bean and the value will be injected by Spring Expression. Find the example files.

spring.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">
	   
     <bean id="calculator" class="com.concretepage.bean.Calculator">
      <property name="randomNum" value="#{ T(java.lang.Math).random() * 50.0 }" />
    </bean>
	
</beans>
 
Calculator.java
package com.concretepage.bean;
public class Calculator {
    private int randomNum = 0;
	public int getRandomNum() {
		return randomNum;
	}
	public void setRandomNum(int randomNum) {
		this.randomNum = randomNum;
	}
}
 
SpringExpressionTest.java
package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.bean.Calculator;
public class SpringExpressionTest {
    public static void main(String... args) {
    	AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    	Calculator ex=(Calculator) context.getBean("calculator");
    	int rnum = ex.getRandomNum();
        System.out.println(rnum);
    } 
}
 
Download Source Code
xml-based-spring-expression-support-for-defining-bean-definitions.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us