Spring @Value使用示例

@PropertySource(“classpath:config.properties”) :指定文件的地址

ELConfig .java

package com.netant.EL;

import java.io.IOException;

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.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;

@Configuration
@ComponentScan("com.netant.EL")
@PropertySource("classpath:config.properties") // 
public class ELConfig {

    @Value("you had a bad day") // 注入普通字符串
    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/?tn=57095150_1_oem_dg") // 注入网址资源
    private Resource testUrl;

    @Value("${jdbc.type}") // 注入配置文件
    private String dataBaseType;

    @Autowired
    private Environment environment; // 注入Properties还可以从Environment中获取

    // 若使用@Value注入,则要配置一个 PropertySourcesPlaceholderConfigurer 的Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
        return new PropertySourcesPlaceholderConfigurer();
    }

    public void outputResource() throws IOException{
        System.out.println(normal);
        System.out.println(osName);
        System.out.println(randomNumber);
        System.out.println(fromAnother);
        System.out.println(IOUtils.toString(testFile.getInputStream()));
        System.out.println(IOUtils.toString(testUrl.getInputStream()));
        System.out.println(dataBaseType);
        System.out.println(environment.getProperty("jdbc.driver"));

    }









}

Main.java

package com.netant.EL;

import java.io.IOException;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ELConfig.class);
        ELConfig eLConfig = context.getBean(ELConfig.class);
        eLConfig.outputResource();
        context.close();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值