Home  >  Spring Core

Annotation Based Spring Expression Support for Defining Bean Definitions

By Arvind Rai, October 05, 2013
Spring expression defines bean input value by annotation and XML. In this page, we will learn how to use Spring Expression to define a bean setter to set a value. To achieve this @Value helps. The bean which needs to be used bears @Value annotation at its setter method. In our example I have shown a complete code how to use annotation based spring expression support for defining bean definitions.

Calculator.java
package com.concretepage.bean;
import org.springframework.beans.factory.annotation.Value;
public class Calculator {
    private int randomNum = 0;
	public int getRandomNum() {
		return randomNum;
	}
	@Value("#{ T(java.lang.Math).random() * 50.0 }")
	public void setRandomNum(int randomNum) {
		this.randomNum = randomNum;
	}
}
 
AppConf.java
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.concretepage.bean.Calculator;
@Configuration
public class AppConf {
	@Bean(name="calc")	
	public Calculator calc(){
		return new Calculator();
	}
}
 
SpringExpressionTest.java
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.bean.Calculator;
public class SpringExpressionTest {
    public static void main(String... args) {
    	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    	ctx.register(AppConf.class);
        ctx.refresh();
        Calculator calc = ctx.getBean(Calculator.class);
    	int rnum = calc.getRandomNum();
        System.out.println(rnum);
    } 
}
 
Download Source Code
annotation-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