Spring筆記 - 資源Resource、表達式語言SpEL

1. 資源Resource

1.1 簡介

一般指文本文件、二進制文件例如圖片、屬性文件properties、配置文件xml等,存放於classpath、文件系統、網絡服務器等位置,經過file:、https:、ftp:等方式獲取。是java.net.URL的加強與擴充。html

1.2 Resource接口與內置實現

Resource接口在Spring普遍使用。其內置實現例如如下。顧名思義,從各自名稱就能夠大體猜想其用途。java

  • UrlResource正則表達式

  • ClassPathResourcespring

  • FileSystemResourceexpress

  • ServletContextResource服務器

  • InputStreamResource網絡

  • ByteArrayResourcedom

1.3 ResourceLoader接口

- 該接口聲明瞭getResource方法,AppCtx實現了該接口。函數

Resource resource = ctx.getResource("x/y/config.txt");

- 資源字符串能夠添加前綴如classpath:、file://、http://,若是不加,將視ctx的類型而定。例如ClassPathXMLAppCtx在classpath查找資源,FileSystemXmlAppCtx在文件系統查找資源。工具

- 若是是FileSystemXmlAppCtx,資源字符串不加file://前綴則爲相對路徑,加了則區分絕對路徑和相對路徑

FileSystemXmlApplicationContext ctx = ...;
//相對路徑
ctx.getResource("path1/userList.txt");
//相對路徑
ctx.getResource("/path1/userList.txt");
//絕對路徑
ctx.getResource("file:///path1/userList.txt");

- 若是不使用ctx,能夠在Bean中注入ResourceLoader

@Autowired
ResourceLoader resourceLoader;

1.4 直接注入Resource

往託管Bean直接注入Resource更加方便

<bean id="car" class="x.y.x.Car">
    <property name="manual" value="doc/manual.txt" />
</bean>


2. 表達式語言SpEL

2.1 簡介

- Spring Expression Language簡稱SpEL,能夠用來在運行時操做對象。同類語言或工具備OGNL、MVEL、JBoss EL等。SpEL在Spring Portfolio裏面應用普遍。

- 其功能例如:字符表達式、布爾和關係操做符、正則表達式、類表達式、訪問properties,arrays,lists,maps、方法調用、關係操做符、賦值、調用構造器、三元操做符、變量、用戶自定義函數、集合投影、集合選擇、模板表達式

2.2 使用方法

//建立parser進行識別
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'.concat('!')");
String message1 = (String) exp.getValue(); //Hello World!
String message2 = (String) exp.getValue(String.class); //指定結果類型,性能更好

//使用EvaluationContext
car.setName("小汽車");
EvaluationContext context = new StandardEvaluationContext(car);
String name = (String) parser.parseExpression("name").getValue(context); //小汽車

//Parser設置
SpelParserConfiguration config = new SpelParserConfiguration(true,true); //arg1:被識別對象爲null時自動建立實例,arg2:被識別對象是collection類型時超過collection上限則自動擴展
ExpressionParser parser = new SpelExpressionParser(config);
class Todo {
    public List<String> items;
}
parser.parseExpression("items[3]").getValue(new Todo()); //返回List<String>,包含4個空字符串

2.3 編譯SpEL

- 對錶達式進行編譯能夠提升性能,Spring reference提到一個例子編譯前50000次迭代耗時75ms,編譯後3ms

- 編譯選項有:OFF(默認)、IMMEDIATE、MIXED

//arg2:在指定classLoader下面建立child classLoader,用來編譯表達式;該classLoader須要可以識別表達式涉及的全部類型。容許null,線程上下文的classLoader將會被用到。
SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, this.getClass().getClassLoader()); 
SpelExpressionParser parser = new SpelExpressionParser(config);

2.4 在IoC容器中使用SpEL

<bean id="randomNumber" class="...">
    <property name="number" value="#{ T(java.lang.Math).random() }" />
</bean>

<bean id="guessNumber" class="...">
    <property name="correctNumber" value="#{ randomNumber.number }" />
</bean>
public class RandomNumber {
    @Value ("#{ T(java.lang.Math).random() }")
    int number;
    
    @Value("#{ systemProperties['user.region'] }")
    public void setDefaultLocale(String defaultLocale) {
        this.defaultLocale = defaultLocale;
    }
}

2.5 語言參考

SpEL有不少支持的表達式,可參考Spring Reference

相關文章
相關標籤/搜索