
- Spring SpEL 教程
- Spring SpEL - 首頁
- Spring SpEL - 概述
- Spring SpEL - 環境設定
- Spring SpEL - 建立專案
- 表示式求值
- Spring SpEL - 表示式介面
- Spring SpEL - EvaluationContext
- Bean 配置
- Spring SpEL - XML 配置
- Spring SpEL - 註解配置
- 語言參考
- Spring SpEL - 字面量表達式
- Spring SpEL - 屬性
- Spring SpEL - 陣列
- Spring SpEL - 列表
- Spring SpEL - 對映
- Spring SpEL - 方法
- 運算子
- Spring SpEL - 關係運算符
- Spring SpEL - 邏輯運算子
- Spring SpEL - 數學運算子
- Spring SpEL - 賦值運算子
- 特殊運算子
- Spring SpEL - 三元運算子
- Spring SpEL - Elvis 運算子
- Spring SpEL - 安全導航運算子
- 集合
- Spring SpEL - 集合選擇
- Spring SpEL - 集合投影
- 其他特性
- Spring SpEL - 建構函式
- Spring SpEL - 變數
- Spring SpEL - 函式
- Spring SpEL - 表示式模板
- Spring SpEL - 有用資源
- Spring SpEL - 快速指南
- Spring SpEL - 有用資源
- Spring SpEL - 討論
Spring SpEL - 基於註解的配置
SpEL 表示式可以用於基於註解的 Bean 配置
語法
以下是在基於註解的配置中使用表示式的示例。
@Value("#{ T(java.lang.Math).random() * 100.0 }") private int id;
這裡我們使用 @Value 註解,並在屬性上指定了一個 SpEL 表示式。類似地,我們也可以在 setter 方法、建構函式和自動裝配期間指定 SpEL 表示式。
@Value("#{ systemProperties['user.country'] }") public void setCountry(String country) { this.country = country; }
以下示例顯示了各種用例。
示例
讓我們更新在Spring SpEL - 建立專案章節中建立的專案。我們新增/更新以下檔案:
Employee.java - 員工類。
AppConfig.java - 配置類。
MainApp.java - 執行和測試的主應用程式。
以下是Employee.java檔案的內容:
package com.tutorialspoint; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Employee { @Value("#{ T(java.lang.Math).random() * 100.0 }") private int id; private String name; private String country; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } @Value("Mahesh") public void setName(String name) { this.name = name; } public String getCountry() { return country; } @Value("#{ systemProperties['user.country'] }") public void setCountry(String country) { this.country = country; } @Override public String toString() { return "[" + id + ", " + name + ", " + country + "]"; } }
以下是AppConfig.java檔案的內容:
package com.tutorialspoint; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = "com.tutorialspoint") public class AppConfig { }
以下是MainApp.java檔案的內容:
package com.tutorialspoint; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MainApp { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(AppConfig.class); context.refresh(); Employee emp = context.getBean(Employee.class); System.out.println(emp); } }
輸出
[84, Mahesh, IN]
廣告