Spring EL 表達式實現資源的注入

前言

Spring 開發中經常涉及調用各種資源的情況,包括普通文件,網址,配置文件,環境變量。使用spring 表達式語言實現資源的注入 ,能夠以一種強大和簡單的方式將值裝配到bean 屬性和構造器中.

特性

spring EL 的特性

  • 使用bean 的id 來引用bean
  • 調用方法和訪問對象的屬性
  • 對值進行算術,關係 和邏輯運算
  • 正則表達式匹配
  • 集合操作

使用

spring主要在@value 的參數中使用表達式,@value可注入以下參數:

1. 普通字符

@Value(12)
private String str;

2.操作系統屬性

@Value("#{systemProperties['os.name']}")
private String osName;
@Value("#{systemProperties['os.name']}")
private static String osName;

3.表達式運算結果

@Value("#{T(java.lang.Math).random() * 100.0}") //隨機數計算值
private Double randomDouble;

4.其他bean的屬性

@Value("#{UserServer.name}")

5.文件內容

@Value(“classpath:test.txt”)
private Resource testFile;

6.網址內容

@Value(“http://www.baidu.com”)
private Resource testUrl;

7.屬性文件

@value("${book.name}")
private String bookName;

測試

package com.blog.www.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

/**
 * SpringBootEL表達式注入測試
 * <br/>
 *
 * @author :leigq
 * @date :2019/8/21 14:42
 */
@Component
public class SpringELAutoWired {

	/**
	 * 普通字符 name = "this is name"
	 */
	@Value("this is name")
	private String name;

	/**
	 * 操作系統屬性
	 */
	@Value("#{systemProperties['os.name']}")
	private String osName;

	/**
	 * 表達式運算結果
	 */
	@Value("#{T(java.lang.Math).random() * 100.0}")
	private Double randomDouble;

	/**
	 * 其他bean的屬性 {@link I18nConfig} 被 spring 管理,spring 注入是類名首字母小寫
	 */
	@Value("#{i18nConfig.ZH_CN}")
	private String otherBeanProperties;

	/**
	 * 文件內容
	 */
	@Value("classpath:banner.txt")
	private Resource banner;

	/**
	 * 網址內容
	 */
	@Value("http://www.baidu.com")
	private Resource webUrl;

	/**
	 * 屬性文件
	 */
	@Value("${spring.profiles.active}")
	private String propertiesName;


	public void test() {
		System.out.println(name);
		System.out.println(osName);
		System.out.println(randomDouble);
		System.out.println(otherBeanProperties);
		System.out.println(banner);
		System.out.println(webUrl);
		System.out.println(propertiesName);
	}

}

package com.blog.www;

import com.blog.www.base.BaseApplicationTests;
import com.blog.www.config.SpringELAutoWired;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;

/**
 * SpringBootEL表達式注入測試
 * <br/>
 *
 * @author :leigq
 * @date :2019/8/21 14:42
 */
public class SpringELAutoWiredTest extends BaseApplicationTests {

	@Autowired
	private SpringELAutoWired springELAutoWired;

	@Test
	public void test() {
		springELAutoWired.test();
	}

}

測試結果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章