如何使用@Value和@PropertySource注入外部资源

1、简介

在Spring Boot进行项目开发的过程中,肯定会有这样一种场景,比如说事件上报,在开发时开发人员可能会模拟在代码中写入一个事件上报Url,然后当部署到生产环境时,该url就需要从外部导入,一般通过修改配置文件的方式达到类似的目的。

在Spring开发中经常涉及调用各种资源的情况,包含普通文件,网址,配置文件,系统环境变量等,这种情况可以使用Spring EL-Spring表达式语言实现资源的注入。

2、实践

程序演示使用IDEA集成开发环境,演示@Value的使用,并通过注解@PropertySource可以注入自定义配置文件或者其他任意新建的文本文件。

注意:以下实践在Spring环境下是通用的,Spring Boot也是可用的的。

2.1项目结构

2.2 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>value</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>value</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

其中

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.3</version>
        </dependency>

依赖可以简化文件相关的操作,本例中使用commons-io将file转换成字符串。

2.3 DemoService

package com.example.value.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 需被注入的类
 *
 * @Owner:
 * @Time: 2019/3/31-12:35
 */
@Service
public class DemoService {
    @Value("其他类的属性")
    private String another;
    public String getAnother() {
        return another;
    }

    public void setAnother(String another) {
        this.another = another;
    }
}

其中在上类中使用@Value注解注入了普通字符串“其他类的属性。”

2.4 ElConfig 类

package com.example.value.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.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;

/**
 * 演示@Value的使用
 *
 * @Owner:
 * @Time: 2019/3/31-12:32
 */
@Configuration
@ComponentScan("com.example.value.service") //扫包
@PropertySource("classpath:test.properties") //注意文件格式的指定
public class ElConfig {
    @Value("I Love You!") //1 注入普通字符串
    private String normal;

    @Value("#{systemProperties['os.name']}") //2 注入操作系统属性
    private String osName;

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

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

    @Value("classpath:test.txt") //5  注入了文件资源
    private Resource testFile;

    @Value("http://www.baidu.com") //6   注入网页资源
    private Resource testUrl;

    @Value("${book.name}") //7   注入classpath:test.properties中资源项,注意美元符号$
    private String bookName;

    @Autowired
    private Environment environment; //7 属性也可以从environment中获取。

    @Bean //7
    public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    public void outputResource() {
        try {
            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(bookName);
            System.out.println(environment.getProperty("book.author"));
            System.out.println(environment.getProperty("book.school"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意:注入配置配件使用@PropertySource指定文件地址,若使用@Value注入,则要配置一个PropertySourcePlaceholderConfigure的Bean

2.5 ValueApplication主类

package com.example.value;
import com.example.value.config.ElConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@SpringBootApplication
public class ValueApplication {
    @Autowired
    private ElConfig config;
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
        ElConfig resourceService = context.getBean(ElConfig.class);

        resourceService.outputResource();
    }
}

2.6 resources下两个文件的内容

2.6.1 test.txt

123334455
aaa
bbb
ccc

2.6.2 test.properties

book.author=sqh
book.name=spring boot
book.school=NJUST

3、控制台打印结果

I Love You! #直接注入字符串
Windows 8.1 #注入了系统属性
87.12913167952843 # 注入了表达式结果
其他类的属性 # 其他类的属性
123334455 # test.txt
aaa
bbb
ccc
<!DOCTYPE html> # 注入了网页内容
<!--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=http://s1.bdstatic.com/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></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://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>

spring boot # 配置文件中的三个值
sqh
NJUST

4、总结

通过上述的方式,也附带的阐述了在Spring Boot中不使用application.properties配置文件,而是用其他任意的配置文件来放入程序配置的使用方法,可以看到@Value很灵活,也很方便,作者暂时比较常用的就是在applicaiton.properties中放入类似book.name这样的配置项而使用@Value("${book.name}")直接注入的方式。

Spring的@PropertySource和@Value注解例子

在这篇文章中,我们会利用Spring的@PropertySource和@Value两个注解从配置文件properties中读取值,以及如何从配置文件中的值转换为List对象。

创建Spring配置Class

@Configurable
@ComponentScan(basePackages = "com.9leg.java.spring")
@PropertySource(value = "classpath:spring/config.properties")
public class AppConfigTest {
    @Bean
    public PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。上面是读取一个配置文件,如果你想要读取多个配置文件,请看下面代码片段:

@PropertySource(value = {"classpath:spring/config.properties","classpath:spring/news.properties"})

在Spring 4版本中,Spring提供了一个新的注解——@PropertySources,从名字就可以猜测到它是为多配置文件而准备的。

@PropertySources({
@PropertySource("classpath:config.properties"),
@PropertySource("classpath:db.properties")
})
public class AppConfig {
 //something
}

另外在Spring 4版本中,@PropertySource允许忽略不存在的配置文件。先看下面的代码片段:

@Configuration
@PropertySource("classpath:missing.properties")
public class AppConfig {
 //something
}

如果missing.properties不存在或找不到,系统则会抛出异常FileNotFoundException。

Caused by: java.io.FileNotFoundException:

class path resource [missiong.properties] cannot be opened because it does not exist

幸好Spring 4为我们提供了ignoreResourceNotFound属性来忽略找不到的文件

@Configuration
 @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)
 public class AppConfig {
  //something
 }
  @PropertySources({
  @PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),
  @PropertySource("classpath:config.properties")
        })

最上面的AppConfigTest的配置代码等于如下的XML配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.9leg.java.spring"/>
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
          <list>
            <value>classpath:spring/config.properties</value>
          </list>
        </property>
      </bean>
</beans>

创建properties配置文件

server.name=9leg,spring
server.id=10,11,12
server.jdbc=com.mysql.jdbc.Driver

创建一个简单的服务

@Component(value = "mockConfigTest")
public class MockConfigTest {
    @Value("#{'${server.name}'.split(',')}")
    private List<String> servers;

    @Value("#{'${server.id}'.split(',')}")
    private List<Integer> serverId;

    @Value("${server.host:127.0.0.1}")
    private String noProKey;

    @Autowired
    private Environment environment;

    public void readValues() {
        System.out.println("Services Size : " + servers.size());
        for(String s : servers)
            System.out.println(s);
        System.out.println("ServicesId Size : " + serverId.size());
        for(Integer i : serverId)
            System.out.println(i);
        System.out.println("Server Host : " + noProKey);
        String property = environment.getProperty("server.jdbc");
        System.out.println("Server Jdbc : " + property);
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AppConfigTest.class);
        MockConfigTest mockConfigTest = (MockConfigTest) annotationConfigApplicationContext.getBean("mockConfigTest");
        mockConfigTest.readValues();
    }
}

首先使用@Component注解声明,接着就是属性字段上的@Value注解,但在这里比较特殊,是通过split()方法,将配置文件中的9leg,spring分割后组成list对象。心细的同学可能注意到了server.host这个key并不存在配置文件中。是的,在这里使用的是默认值,即127.0.0.1,它的格式是这样的。

@value("${key:default}")
private String var;

然后注入了Environment,可以通过getProperty(key)来获取配置文件中的值。 运行main方法,来看下输出结果:

Services Size : 2
9leg
spring
ServicesId Size : 3
10
11
12
Server Host : 127.0.0.1
Server Jdbc : com.mysql.jdbc.Driver

最后要说一点,在main方法中请使用

new AnnotationConfigApplicationContext(AppConfigTest.class)

来代替

new ClassPathXmlApplicationContext(“applicationContext.xml”)

或者

new FileSystemXmlApplicationContext(“src/main/resources/applicationContext.xml”)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解Spring通过@Value注解注入属性的几种方式

    场景 假如有以下属性文件dev.properties, 需要注入下面的tag tag=123 通过PropertyPlaceholderConfigurer <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="dev.properties" /&

  • Spring 开发过程中Value 注解的使用场景

    Spring 开发过程中使用 Value 注解对属性进行赋值:常见的场景有三种. 直接对属性进行赋值:包括普通字符串.操作系统属性.文件内容等. 从配置文件中读取简单类型进行赋值:配置文件需要生效才可. 从配置文件中读取复杂类型进行赋值:如数组.Map.对象列表等. 一.直接对属性进行赋值 通过 @Value 将外部的值动态注入到Bean中,使用的情况有: 注入普通字符串 注入操作系统属性 注入表达式结果 注入其他Bean属性:注入beanInject对象的属性another 注入文件资源 注入

  • Spring @value和@PropertySource注解使用方法解析

    这篇文章主要介绍了Spring @value和@PropertySource注解使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 @Value注解:可以使用注入基本字符串 EL表达式,从配置文件读取数据 @PropertySource用于引入单个配置文件 @PropertySources用于引入多个配置文件 @PropertySource或者@PropertySources引入的数据都是存在环境变量ConfigurableEnviro

  • Spring@Value属性注入使用方法解析

    这篇文章主要介绍了Spring@Value属性注入使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在使用Spring框架的项目中,@Value是使用比较频繁的注解之一,它的作用是将配置文件中key对应的值赋值给它标注的属性.在日常使用中我们常用的功能都比较简单,本篇文章系统的带大家来了解一下@Value的使用方法. @Value注入支持形式 @Value属性注入功能根据注入的内容来源可分为两类:通过配置文件的属性注入和通过非配置文件

  • 如何使用@Value和@PropertySource注入外部资源

    1.简介 在Spring Boot进行项目开发的过程中,肯定会有这样一种场景,比如说事件上报,在开发时开发人员可能会模拟在代码中写入一个事件上报Url,然后当部署到生产环境时,该url就需要从外部导入,一般通过修改配置文件的方式达到类似的目的. 在Spring开发中经常涉及调用各种资源的情况,包含普通文件,网址,配置文件,系统环境变量等,这种情况可以使用Spring EL-Spring表达式语言实现资源的注入. 2.实践 程序演示使用IDEA集成开发环境,演示@Value的使用,并通过注解@Pr

  • Java 读取外部资源的方法详解及实例代码

    Java 读取外部资源的方法详解 在Java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下. 1.从当前的工作目录中读取: try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("wkdir.txt"))); String str; while ((str = in.readLine())

  • vue实践---vue不依赖外部资源实现简单多语操作

    vue使用多语,最常见的就是 vue-i18n, 但是如果开发中的多语很少,比如就不到10个多语,这样就没必要引入vue-i18n了, 引入了反正导致代码体积大了,这时候单纯用vue实现多语就是比较好的选择. 第一步 首先建立一个locales.js 存放多语语言包的内容,这里只写了 zh-CN, en这两种语言,其他还想新增的话 方法一样,代码如下: export default { 'zh-CN': { name: '我是中文名字' }, 'en': { name: 'I am Englis

  • springboot如何通过URL方式访问外部资源

    目录 springboot通过URL方式访问外部资源 第一种 第二种 springboot通过URL访问本地文件 springboot通过URL方式访问外部资源 遇到这个问题时翻阅百度,无外乎就是两种方式 第一种 在springboot 2.1.8中该方法已过时 第二种 这个方法是可以实现通过url访问到指定目录下的文件,但是使用spring.resources.static-locations这个配置会覆盖掉SpringBoot默认的静态资源文件夹,项目的静态资源全都无法访问,而spring.

  • jsp、css中引入外部资源相对路径问题分析

    在jsp页面中添加base,可用相对路径: 复制代码 代码如下: <%     String path = request.getContextPath();     String basePath = request.getScheme() + "://"             + request.getServerName() + ":" + request.getServerPort()             + path + "/&quo

  • Java JDK1.5、1.6、1.7新特性整理

    一.Java JDK1.5的新特性 1.泛型: List<String> strs = new ArrayList<String>();//给集合指定存入类型,上面这个集合在存入数据的时候必须存入String类型的数据,否则编译器会报错 2.for-each 例如上面这个集合我们可以通过for-each遍历,这样更加简单清晰 for(String s : strs){ System.out.println(s); } 注意:使用for-each遍历集合时,要遍历的集合必须实现了It

  • 使用@PropertySource读取配置文件通过@Value进行参数注入

    目录 @PropertySource读取配置文件通过@Value参数注入 Spring读取配置@Value.@PropertySource.@ConfigurationProperties使用 @Value @Value中$和#的区别 @PropertySource:加载配置属性源 @ConfigurationProperties @PropertySource读取配置文件通过@Value参数注入 有参数文件如下test.properties project.author=wpfc projec

  • 详解SpringBoot注入数据的方式

    关于注入数据说明 1.不通过配置文件注入数据 通过@Value将外部的值动态注入到Bean中,使用的情况有: 注入普通字符串 注入操作系统属性 注入表达式结果 注入其他Bean属性:注入Student对象的属性name 注入文件资源 注入URL资源 辅助代码 package com.hannpang.model; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereo

  • Spring使用@Value注解与@PropertySource注解加载配置文件操作

    1.@Value注解简介 Spring框架提供的@Value注解可以将外部的值动态注入到Bean中,@Value注解使用在字段.构造器参数和方法参数上. @Value可以指定属性取值的表达式,支持通过#{}使用SpringEL来取值,也支持使用${}来将属性来源中(Properties文件.本地环境变量.系统属性等)的值注入到Bean的属性中. 此注解值的注入发生在AutowiredAnnotationBeanPostProcessor类中. @Value注解实现以下几种情况: (1)注入普通字

  • AngularJS学习第二篇 AngularJS依赖注入

    简介: 首先我们需要理解什么是依赖注入? 控制反转和依赖注入有什么区别? 假定:应用程序A,需要访问外部资源C.这里使用了容器B(是指用来实现 IOC/DI 功能的一个框架程序). A需要访问C B获取C然后返回给A IOC inversion of control 控制反转:站在容器角度.B控制A,由B反向的向A注入C.即容器控制应用程序,由容器反向的向应用程序注入应用程序所需要的外部资源. DI Dependency Injection 依赖注入:站在应用程序的角度.A依赖B获取C,B将C注

随机推荐