Spring EL

百聯達發表於2017-02-16
一:說明

Spring EL-Spring表示式語言,支援在xml和註解中使用表示式,類似於JSP的EL表示式語言。

Spring 開發中經常涉及呼叫各種資源的情況,包含普通檔案,網址,配置檔案,系統環境變數等。 我們可以使用Spring的表示式語言實現資源的注入。

二:程式碼例項


點選(此處)摺疊或開啟

  1. @Service
  2. public class DemoService {
  3.     @Value("其他類的屬性")
  4.     private String another;

  5.     /**
  6.      * @return the another
  7.      */
  8.     public String getAnother() {
  9.         return another;
  10.     }

  11.     /**
  12.      * @param another
  13.      * the another to set
  14.      */
  15.     public void setAnother(String another) {
  16.         this.another = another;
  17.     }

  18. }


點選(此處)摺疊或開啟

  1. @Configuration
  2. @ComponentScan("com.gemdale")
  3. @PropertySource("classpath:com/gemdale/gmap/spring/boot/demo/el/test.properties")
  4. public class ElConfig {
  5.     @Value("I love youe!")
  6.     private String normal;

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

  9.     @Value("#{ T(java.lang.Math).random() * 100.0 }")
  10.     private double randomNumber;

  11.     @Value("#{demoService.another}")
  12.     private String fromAnother;

  13.     @Value("classpath:com/gemdale/gmap/spring/boot/demo/el/test.txt")
  14.     private Resource testFile;

  15.     @Value("")
  16.     private Resource testUrl;

  17.     @Value("${book.name}")
  18.     private String bookName;

  19.     @Autowired
  20.     private Environment environment;

  21.     @Bean
  22.     public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
  23.         return new PropertySourcesPlaceholderConfigurer();
  24.     }

  25.     public void outputResource() {
  26.         try {
  27.             System.out.println(normal);
  28.             System.out.println(osName);
  29.             System.out.println(randomNumber);
  30.             System.out.println(fromAnother);
  31.             System.out.println(IOUtils.toString(testFile.getInputStream()));
  32.             System.out.println(IOUtils.toString(testUrl.getInputStream()));
  33.             System.out.println(bookName);
  34.             System.out.println(environment.getProperty("book.author"));
  35.         }
  36.         catch (Exception e) {
  37.            e.printStackTrace();
  38.         }
  39.     }
  40. }

點選(此處)摺疊或開啟

  1. public class Start {
  2.     public static void main(String[] args) throws Exception {

  3.         AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(
  4.                 ElConfig.class);
  5.         ElConfig resourceService = configApplicationContext.getBean(ElConfig.class);
  6.         resourceService.outputResource();

  7.         configApplicationContext.close();
  8.     }
  9. }



點選(此處)摺疊或開啟

  1. book.author=GH
  2. book.name=spring boot


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28624388/viewspace-2133687/,如需轉載,請註明出處,否則將追究法律責任。

相關文章