Spring Bean引用例子
如何注入值到Spring bean屬性
Spring bean加載多個配置文件
Spring內部bean實例
Spring Bean作用域實例
Spring集合 (List,Set,Map,Properties) 實例
Spring ListFactoryBean實例
Spring SetFactoryBean實例
Spring MapFactoryBean例子
Spring注入日期到bean屬性-CustomDateEditor
Spring PropertyPlaceholderConfigurer實例
Spring bean配置繼承
Spring依賴檢查
Spring使用@Required註解依賴檢查
Spring自定義@Required-style註解
Spring Bean InitializingBean和DisposableBean實例
Spring Bean init-method 和 destroy-method實例
Spring @PostConstruct和@PreDestroy實例
Spring EL正則表達式實例
Spring EL支持正則表達式,可使用一個簡單的關鍵詞「matches」。如下實例,
@Value("#{'100' matches '\\d+' }")
private boolean isDigit;
它測試'100'是否是通過正則表達式‘\\d+‘測試過的一個有效的數字。
Spring EL以註解的形式
請參閱下面的 Spring EL 正則表達式的例子,這裏有部分摻入三元運算符,這使得 Spring EL 非常靈活,功能強大。
下面的例子應該是不言自明的。
package com.yiibai.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
// email regular expression
String emailRegEx = "^\[\_A-Za-z0-9-\]+(\\\\.\[\_A-Za-z0-9-\]+)" +
"\*@\[A-Za-z0-9\]+(\\\\.\[A-Za-z0-9\]+)\*(\\\\.\[A-Za-z\]{2,})$";
// if this is a digit?
@Value("#{'100' matches '\\\\d+' }")
private boolean validDigit;
// if this is a digit + ternary operator
@Value("#{ ('100' matches '\\\\d+') == true ? " +
"'yes this is digit' : 'No this is not a digit' }")
private String msg;
// if this emailBean.emailAddress contains a valid email address?
@Value("#{emailBean.emailAddress matches customerBean.emailRegEx}")
private boolean validEmail;
//getter and setter methods, and constructor
}
package com.yiibai.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("emailBean")
public class Email {
@Value("[email protected]")
String emailAddress;
//...
}
輸出
Customer [isDigit=true, msg=yes this is digit, isValidEmail=true]
Spring EL以XML的形式
請參閱在XML文件定義bean的等效版本。
<bean id="customerBean" class="com.yiibai.core.Customer">
<property name="validDigit" value="#{'100' matches '\\d+' }" />
<property name="msg"
value="#{ ('100' matches '\\d+') == true ? 'yes this is digit' : 'No this is not a digit' }" />
<property name="validEmail"
value="#{emailBean.emailAddress matches '^\[\_A-Za-z0-9-\]+(\\.\[\_A-Za-z0-9-\]+)\*@\[A-Za-z0-9\]+(\\.\[A-Za-z0-9\]+)\*(\\.\[A-Za-z\]{2,})$' }" />
</bean>
<bean id="emailBean" class="com.yiibai.core.Email">
<property name="emailAddress" value="[email protected]" />
</bean>
下載代碼 – http://pan.baidu.com/s/1jHklXt0
參考
- Spring EL三元運算符(if-then-else)實例