1. 程式人生 > >【Spring】Spring常用配置-Spring EL和資源呼叫

【Spring】Spring常用配置-Spring EL和資源呼叫

分析

先簡單介紹下Spring EL。
Spring EL 也就是Spring表示式語言,支援在xml和註解中使用表示式,類似於JSP的EL表示式語言。

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

Spring主要在註解@Value的引數中使用表示式。

本示例演示實現以下幾種情況:
1、注入普通的字串
2、注入作業系統屬性
3、注入表示式運算結果
4、注入其他Bean的屬性
5、注入檔案內容
6、注入網址內容
7、注入屬性檔案

示例

因為需要將file轉換成字串,我們增加commons-io可以簡化檔案的相關操作、
在pom檔案中增加如下程式碼:

<!--簡化檔案操作-commons-io-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

然後,在當前類的目錄下新建test.txt。內容隨意。
我的內容如下:

測試檔案內容:Spring

然後再新建test.properties檔案,內容如下,當然,你也可以自己修改:

project.name=SpringEL
project.author=chenhaoxiang

寫需要被注入的Bean:

package cn.hncu.p2_2_2SpringEL;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * User: 陳浩翔.
 * Date: 2016/11/13.
 * Time: 下午 9:06.
 * Explain:被注入的Bean
 */
@Service public class DemoService { @Value("DemoService類的屬性")//注入字串 private String another; public String getAnother() { return another; } public void setAnother(String another) { this.another = another; } }

增加配置類:

package cn.hncu.p2_2_2SpringEL;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: 陳浩翔.
 * Date: 2016/11/13.
 * Time: 下午 9:11.
 * Explain:配置類
 */
@Configuration
@ComponentScan("cn.hncu.p2_2_2SpringEL")
@PropertySource("classpath:cn/hncu/p2_2_2SpringEL/test.properties")
public class ElConfig {

    @Value("I LOVE YOU!")//注入字串
    private String normal;

    @Value("#{systemProperties['os.name']}")//獲取作業系統名
    private String osName;

    @Value("#{ T(java.lang.Math).random() * 100.0 }")//注入表示式結果
    private double randomNumber;

    @Value("#{demoService.another}")//注入其他Bean的屬性
    private String fromAnother;

    @Value("${project.name}")//注入配置檔案
    private String projectName;

    @Value("classpath:cn/hncu/p2_2_2SpringEL/test.txt")
    private Resource testFile;//注意這個Resource是:org.springframework.core.io.Resource;

    @Autowired //注入配置檔案
    private Environment environment;

    @Value("http://www.chaojijuhui.com")//注入網址資源
    private Resource testUrl;

    @Bean //注入配置檔案
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

    public void outputResource(){
        try {
            System.out.println("normal:"+normal);
            System.out.println("osName:"+osName);
            System.out.println("randomNumber:"+randomNumber);
            System.out.println("fromAnother:"+fromAnother);
            System.out.println("projectName:"+projectName);
            System.out.println("測試檔案:"+IOUtils.toString(testFile.getInputStream()));
            System.out.println("配置檔案project.author:"+environment.getProperty("project.author"));
            System.out.println("網址資源:"+IOUtils.toString(testUrl.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

注入配置配件需要使用@PropertySource指定檔案地址,若使用@Value注入,則要配置一個PropertySourcesPlaceholderConfigurer的Bean。
注意,@Value(“${project.name}”)使用的是”$“而不是”#”。
上面的類演示了這2中配置配件的方式!

執行類:

package cn.hncu.p2_2_2SpringEL;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created with IntelliJ IDEA.
 * User: 陳浩翔.
 * Date: 2016/11/13.
 * Time: 下午 11:44.
 * Explain:執行類
 */
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
        ElConfig resourceService = context.getBean(ElConfig.class);
        resourceService.outputResource();
        context.close();
}

}

執行結果:

本文章由[諳憶]編寫, 所有權利保留。