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]
廣告