使用@Value注入表達式


在配置類中使用@PropertySource注解讀取外部的資源配置文件:

 

使用@Value注入表達式:

1.注入普通字符

  @Value("注入普通字符")

2.注入操作系統屬性

    @Value(#{SystemProperties['os.name']})

3.表達式

     @Value(#T(java.lang.Math).random()*100.0)

4.其他Bean的屬性

      @Value("#{其他Bean的name.其他Bean的屬性}")

5. 文件資源

      @Value("classpath:其他文件的路徑")

6.網址資源

       @Value("www.baidu.com")

7.其他配置文件的屬性,注意這個使用$,而不是#

        @Value("${book.name}")

 

test.properties

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

 

test.txt中文本任意

 

配置類SpringConfig.java

package config;

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.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import repository.dao.UserDAO;
import service.DemoService;
import service.FunctionService;
import service.UseFunctionService;

import java.io.IOException;


@Configuration
@ComponentScan(basePackages = "main.java.com.example.demo")
@PropertySource(value={"test.properties"})
public class SpringConfig {

    @Bean // 通過該注解來表明是一個Bean對象,相當於xml中的<bean>
    public DemoService demoService(){
        return new DemoService(); // 直接new對象做演示
    }

    @Value("注入普通字符串")// 注入普通字符串
    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("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;//屬性文件

    @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;
        }
    }
}

 

測試類

 1 import config.SpringConfig;
 2 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 3 import repository.entity.User;
 4 import service.DemoService;
 5 import service.UseFunctionService;
 6 import service.UserService;
 7 
 8 import java.util.List;
 9 
10 public class Main {
11     
12     public static void main(String[] args) {
13         // 通過Java配置來實例化Spring容器
14         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
15 
16         SpringConfig config=context.getBean(SpringConfig.class);
17         System.out.println(config.toString());
18         // 銷毀該容器
19         context.destroy();
20     } 
21 }

 

輸出結果

 
         

SpringConfig [

normal=注入普通字符串,

osName=Windows 10,

randomNumber=90.51228169713467,

fromAnother=其他類的屬性,

testFile=測試文本,

testUrl=<!DOCTYPE html>  //百度登錄首頁的html文本
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@728938a9: startup date [Thu Dec 07 15:55:23 CST 2017]; root of context hierarchy
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class="head_wrapper"> <div class="s_form"> <div class="s_form_wrapper"> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class="fm"> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class="s_ipt" value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class="mnav">新聞</a> <a href=https://www.hao123.com name=tj_trhao123 class="mnav">hao123</a> <a href=http://map.baidu.com name=tj_trmap class="mnav">地圖</a> <a href=http://v.baidu.com name=tj_trvideo class="mnav">視頻</a> <a href=http://tieba.baidu.com name=tj_trtieba class="mnav">貼吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class="lb">登錄</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登錄</a>');
</script> <a href=//www.baidu.com/more/ name=tj_briicon class="bri" style="display: block;">更多產品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>關於百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必讀</a>&nbsp; <a href=http://jianyi.baidu.com/ class="cp-feedback">意見反饋</a>&nbsp;京ICP證030173號&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

 

bookName=spring boot,

environment=spring boot]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM