Spring EL 表达式实现资源的注入

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_34845394/article/details/99958493

前言

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();
	}

}

测试结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34845394/article/details/99958493
今日推荐