歡迎您光臨本站 註冊首頁

Spring EL表示式的運用@Value說明

←手機掃碼閱讀     火星人 @ 2020-04-28 , reply:0

Spring EL表達式語言,支持在XML和註解中表達式,類是於JSP的EL表達式語言。

在Spring開發中經常涉及調用各種資源的情況,包含普通文件、網址、配置文件、系統環境變量等,我們可以使用Spring的表達式語言實現資源的注入。

Spring主要在註解@value的參數中使用表達式。

本事咧演示一下情況:

注入普通字符串

注入操作系統屬性

注入表達式運算結果

注入其他Bean的屬性

注入文件內容

注入網址內容

注入屬性文件(注意:用的是$符號)

配置文件test.properties:

book.author=wangyunfei

book.name=spring boot

測試文件test.text:

你好!Spring boot

注入類:

@Configuration // 聲明當前類是一個配置類,相當於Spring配置的XML文件 // 包掃描,並排除了對BeanConfig的掃描 @ComponentScan(basePackages={"com.chenfeng.xiaolyuh"}, excludeFilters={@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value={BeanConfig.class, AopConfig.class})}) @PropertySource("classpath:test.properties")// 指定文件地址 public class ELConfig { @Value("注入普通字符串")// 注入普通字符串 private String normal; @Value("#{systemProperties['os.name']}")// 注入操作系統屬性 private String osName; @Value("#{T(java.lang.Math).random() * 100.0 }")// 注入表達式結果 private double randomNumber; @Value("#{demoELService.another}")// 注入其他Bean屬性 private String fromAnother; @Value("classpath:test.txt")// 注入文件資源 private Resource testFile; @Value("https://www.baidu.com")// 注入網址資源 private Resource testUrl; @Value("${book.name}")// 注入配置文件【注意是$符號】 private String bookName; @Autowired// Properties可以從Environment獲得 private Environment environment; // @Bean // public static PropertySourcesPlaceholderConfigurer propertyConfigure() { // return new PropertySourcesPlaceholderConfigurer(); // } @Override public String toString() { try { return "ELConfig [normal=" + normal + ", osName=" + osName + ", randomNumber=" + randomNumber + ", fromAnother=" + fromAnother + ", testFile=" + IOUtils.toString(testFile.getInputStream()) + ", testUrl=" + IOUtils.toString(testUrl.getInputStream()) + ", bookName=" + bookName + ", environment=" + environment.getProperty("book.name") + "]"; } catch (IOException e) { e.printStackTrace(); return null; } } }

測試類:

public class SpringELTest { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ELConfig.class); @Test public void contextTest() { ELConfig elConfig = context.getBean(ELConfig.class); System.out.println(elConfig.toString()); } @After public void closeContext() { context.close(); } }

補充知識:yml、properties獲取pom自定義變量

pom變量:

devdevjdbc:mysql://127.0.0.1:3306/melab?allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaijdbc:mysql://127.0.0.1:3306/tx-manager?allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghairoot123456



yml獲取pom變量:

添加依賴:



org.yamlsnakeyaml1.25



獲取變量:

url: @jdbc-url@ lcn-log-url: @jdbc-url@ username: @jdbc-user@ password: @jdbc-password@ properties獲取pom變量:

build設置:

maven-resources-pluginutf-8true



獲取變量:

spring.datasource.url=${jdbc-url} spring.datasource.username=${jdbc-user} spring.datasource.password=${jdbc-password}



[火星人 ] Spring EL表示式的運用@Value說明已經有402次圍觀

http://coctec.com/docs/java/show-post-231879.html