首页 > 技术文章 > 使用@Value注入表达式

cyxdn 2017-12-07 16:09 原文

在配置类中使用@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]

 

推荐阅读