天天看點

Spring EL表示式的運用@Value

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

}      

繼續閱讀