Spring 已经盛行多年,目前已经处于3.0阶段,关于Spring的概念介绍性的东西网上已经很多,本系列博客主要是把一些知识点通过代码的方式总结起来,以便查阅.
作为入门,本篇主要介绍SPEL的使用.
SPEL(Spring Expression Language)是Spring 3引入的一个新特性,通过使用SPEL可以在程序运行的过程中,动态的对BEAN的属性进行赋值,话不多说,请看代码以及注释
入口类
package com.eric.introduce.spel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 主要用来演示SPEL的用法
*
* @author Eric
*
*/
public class SpelCaller {
private static final String CONFIG = "com/eric/introduce/spel/spel.xml";
private static ApplicationContext context = new ClassPathXmlApplicationContext(
CONFIG);
public static void main(String[] args) {
//下面的几个方法主要是和操作Bean相关
getNormalValue();
getOtherBeanProperties();
callOtherBeanMethod();
getOtherBeanPropertiesByCheckSafe();
getPropertiesByStaticField();
//下面的几个方法主要是和操作集合相关
getPropertyFromList();
getAddressFromListByRandom();
getAddressFromMap();
getPropertiesFromProperties();
getCityListByCondiciton();
getFilterResult1st();
getFilterResultLast();
getFilterResultFieldList();
}
/**
* 打印几个常数值
*/
public static void getNormalValue() {
Student testClass = (Student) context.getBean("eric");
System.out.println(testClass.getName());
System.out.println(testClass.getAge());
System.out.println(testClass.isGender());
}
/**
* 利用SPEL从别的Bean属性中获得属性值
*/
public static void getOtherBeanProperties() {
Student testClass = (Student) context.getBean("eric");
System.out.println(testClass.getAddress());
}
/**
* 利用SPEL从别的Bean的方法调用中获得属性值
*/
public static void callOtherBeanMethod() {
Student testClass = (Student) context.getBean("eric");
System.out.println(testClass.getEmail());
}
/**
* get properties value by "Check Safe"
*/
public static void getOtherBeanPropertiesByCheckSafe() {
Student testClass = (Student) context.getBean("eric");
System.out.println(testClass.getDescription());
}
/**
* get properties value by static field/Method 此外这个例子中还演示了SPEL还支持
* 算数运算(+,-,*,/....) 关系运算(<,>,==,<=,>=...) 逻辑运算(and,or,not) 条件运算( :)
* 正则表达式(matches)
* */
public static void getPropertiesByStaticField() {
Student testClass = (Student) context.getBean("eric");
System.out.println(testClass.getRandomId());
System.out.println(testClass.getPi());
}
/**
* 利用SPEL随机从列表中选择一个地址
*/
public static void getPropertyFromList() {
Student testClass = (Student) context.getBean("getAddressFromList");
System.out.println(testClass.getCity());
}
/**
* 利用SPEL随机从列表中随机一个地址
*/
public static void getAddressFromListByRandom() {
Student testClass = (Student) context
.getBean("getAddressFromListByRandom");
System.out.println(testClass.getCity());
}
/**
* 利用SPEL从Map中选择一个地址
*/
public static void getAddressFromMap() {
Student testClass = (Student) context.getBean("getAddressFromMap");
System.out.println(testClass.getCity());
}
/**
* 利用SPEL从properties选择地址
*/
public static void getPropertiesFromProperties() {
Student testClass = (Student) context
.getBean("getPropertiesFromProperties");
System.out.println(testClass.getUsername());
System.out.println(testClass.getPwd());
}
/*