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

目录
  • @PropertySource读取配置文件通过@Value参数注入
  • Spring读取配置@Value、@PropertySource、@ConfigurationProperties使用
    • @Value
      • @Value中$和#的区别
    • @PropertySource:加载配置属性源
    • @ConfigurationProperties

@PropertySource读取配置文件通过@Value参数注入

有参数文件如下test.properties

project.author=wpfc
project.create_time=2018/3/29

在系统中读取对应的数据,并注入到属性中

@Configuration
@ComponentScan("cn.edu.ntu")
@PropertySource("classpath:test.properties")
public class ElConfig {
 
    @Value("#{systemProperties['os.name']}")
    private String osName;
    
    //要想使用@Value 用${}占位符注入属性,这个bean是必须的(PropertySourcesPlaceholderConfigurer),
    //这个就是占位bean,
    //另一种方式是不用value直接用Envirment变量直接getProperty('key')  
    @Value("${project.author}")
    public String author;
    
    @Autowired
    private Environment environment;
    
    //You need this if you use @PropertySource + @Value
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }
    
    public void printProperties(){
        System.out.println("os name : " + osName);
        System.out.println("author  : " + author);
        System.out.println("env     : " + environment.getProperty("project.create_time"));
    }    
}

测试方法:

public class MainApplication {
    public static void main(String[] args){
        AnnotationConfigApplicationContext context = null;
        context = new AnnotationConfigApplicationContext(ElConfig.class);
        ElConfig bean = context.getBean(ElConfig.class);
        bean.printProperties();
    }    
}

测试结果:

os name : Windows 7author  : wpfcenv     : 2018/3/29

  • @Import引入javaConfig配置的配置类
  • @ImportResource引入xml对应的配置文件

Spring读取配置@Value、@PropertySource、@ConfigurationProperties使用

Spring (Boot)获取参数的方式有很多,其中最被我们熟知的为@Value了,它不可谓不强大。

今天就针对我们平时最长使用的@Value,以及可能很少人使用的@PropertySource、@ConfigurationProperties等相关注解进行一个详细的扫盲,希望能够帮助到到家,使用起来更加顺畅

@Value

@Value注解的注入非常强大,可以借助配置文件的注入、也可以直接注入

注入普通字符串

    @Value("normal")
    private String normal; // normal (显然这种注入的意义不大)

注入操作系统属性

@Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; 
//效果等同于  是因为spring模版把系统变量否放进了Enviroment
@Value("${os.name}")
    private String systemPropertiesName;

注入表达式结果

@Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; //41.29185128620939

注入其它Bean的属性:Person类的name属性

    @Bean
    public Person person() {
        Person person = new Person();
        person.setName("fangshixiang");
        return person;
    }
 
//注入属性
    @Value("#{person.name}")
    private String personName;
 
    @Test
    public void contextLoads() {
        System.out.println(personName); //fangshixiang
    }

注入文件资源

在resources下放置一个jdbc.properties配置文件。然后可以直接注入

    @Value("classpath:jdbc.properties")
    private Resource resourceFile; // 注入文件资源
 
    @Test
    public void contextLoads() throws IOException {
        System.out.println(resourceFile); //class path resource [jdbc.properties]
        String s = FileUtils.readFileToString(resourceFile.getFile(), StandardCharsets.UTF_8);
        System.out.println(s);
        //输出:
        //db.username=fangshixiang
        //db.password=fang
        //db.url=jdbc:mysql://localhost:3306/mytest
        //db.driver-class-name=com.mysql.jdbc.Driver
    }

注入Url资源

    @Value("http://www.baidu.com")
    private Resource testUrl; // 注入URL资源 
 
    @Test
    public void contextLoads() {
        System.out.println(testUrl); //URL [http://www.baidu.com]
    }

@Value中$和#的区别

语法:

${ properties }和#{ SpEL }的语法区别

${ property : default_value }

#{ obj.property? : default_value } 表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法。当然还有可以表示常量

正常使用的情况,这里不做过多的介绍了,现在介绍一些异常情况

${ properties }`:这种比较简单,如果key找不到,启动会失败。如果找不到的时候也希望正常启动,可以采用冒号+默认值的方式

#{ obj.property? : default_value }

    @Value("#{person}")
    private Person value;

    @Test
    public void contextLoads() {
        System.out.println(value); //Person(name=fangshixiang, age=null, addr=null, hobby=null)
    }

我们发现这个很强大,可以直接把容器的里的一个对象直接注入进来。只是我们可能一般不这么做。

如果改成person1,在容器里找不到这个bean,也是会启动报错的。@Value("#{person1?:null}")这样也是不行的,因为person1找不到就会报错

    @Value("#{person.name}")
    private String personName;

    @Value("#{person.age}")
    private String perAge;

    //注入默认值
    @Value("#{person.age?:20}")
    private String perAgeDefault;

    //如果age22这个key根本就不存在,启动肯定会报错的
    //@Value("#{person.age22?:20}")
    //private String perAgeDefault22;

    @Test
    public void contextLoads() {
        System.out.println(personName); //fangshixiang
        System.out.println(perAge); //null
        System.out.println(perAgeDefault); //20
    }

获取级联属性,下面两种方法都是ok的:

    @Value("#{person.parent.name}")
    private String parentName1;

    @Value("#{person['parent.name']}")
    private String parentName2;

    @Test
    public void contextLoads() {
        System.out.println(parentName1); //fangshixiang
        System.out.println(parentName2); //fangshixiang
    }

二者结合使用:#{ ‘${}’ }

注意结合使用的语法和单引号,不能倒过来。

两者结合使用,可以利用SpEL的特性,写出一些较为复杂的表达式,如:

    @Value("#{'${os.name}' + '_' +  person.name}")
    private String age; 

    @Test
    public void contextLoads() {
        System.out.println(age); //Windows 10_fangshixiang
    }

@PropertySource:加载配置属性源

此注解也是非常非常的强大,用好了,可以很好的实现配置文件的分离关注,大大提高开发的效率,实现集中化管理

最简单的应用,结合@Value注入属性值(也是最常见的应用)

通过@PropertySource把配置文件加载进来,然后使用@Value获取

@Configuration
@PropertySource("classpath:jdbc.properties")
public class PropertySourceConfig {

    @Value("${db.url}")
    private String dbUrl;

    @PostConstruct
    public void postConstruct() {
        System.out.println(dbUrl); //jdbc:mysql://localhost:3306/mytest
    }
}

@PropertySource各属性介绍

  • value:数组。指定配置文件的位置。支持classpath:和file:等前缀 Spring发现是classpath开头的,因此最终使用的是Resource的子类ClassPathResource。如果是file开头的,则最终使用的类是FileSystemResource
  • ignoreResourceNotFound:默认值false。表示如果没有找到文件就报错,若改为true就不报错。建议保留false
  • encoding:加载进来的编码。一般不用设置,可以设置为UTF-8等等
  • factory:默认的值为DefaultPropertySourceFactory.class。
	@Override
	public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
		return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
	}

源码其实也没什么特别的。其重难点在于:

1、DefaultPropertySourceFactory什么时候被Spring加载呢?

2、name和resource都是什么时候被赋值进来的?

本文抛出这两个问题,具体原因会在后续分析源码的相关文章中有所体现。

需要注意的是PropertySourceFactory的加载时机早于Spring Beans容器,因此实现上不能依赖于Spring的IOC。

@PropertySource多环境配置以及表达式使用(spring.profiles.active)

方法一:可以这么配置

@PropertySource(“classpath:jdbc-${spring.profiles.active}.properties”)

程序员在开发时不需要关心生产环境数据库的地址、账号等信息,一次构建即可在不同环境中运行

@ConfigurationProperties

注意:上面其实都是Spring Framwork提供的功能。而@ConfigurationProperties是Spring Boot提供的。包括@EnableConfigurationProperties也是Spring Boot才有的。它在自动化配置中起到了非常关键的作用

ConfigurationPropertiesBindingPostProcessor会对标注@ConfigurationProperties注解的Bean进行属性值的配置。

有时候有这样子的情景,我们想把配置文件的信息,读取并自动封装成实体类,这样子,我们在代码里面使用就轻松方便多了,这时候,我们就可以使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类

该注解在Spring Boot的自动化配置中得到了大量的使用

如SpringMVC的自动化配置:

@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {}

//加载方式
	@Configuration
	@Conditional(DefaultDispatcherServletCondition.class)
	@ConditionalOnClass(ServletRegistration.class)
	// 此处采用这个注解,可议把WebMvcProperties这个Bean加载到容器里面去~~~
	// WebMvcProperties里面使用了`@ConfigurationProperties(prefix = "spring.mvc")`
	@EnableConfigurationProperties(WebMvcProperties.class) //加载MVC的配置文件
	protected static class DispatcherServletConfiguration {}

似乎我们能看出来一些该注解的使用方式。

说明:这里说的两种,只是说的最常用的。其实只要能往容器注入Bean,都是一种方式,比如上面的@EnableConfigurationProperties方式也是ok的

关于@EnableConfigurationProperties的解释,在注解驱动的Spring相关博文里会有体现

加在类上,需要和@Component注解,结合使用.代码如下

com.example.demo.name=${aaa:hi}
com.example.demo.age=11
com.example.demo.address[0]=北京  # 注意数组 List的表示方式 Map/Obj的方式各位可以自行尝试
com.example.demo.address[1]=上海
com.example.demo.address[2]=广州
com.example.demo.phone.number=1111111

java代码:

@Component
@ConfigurationProperties(prefix = "com.example.demo")
public class People {
 
    private String name;
    private Integer age;
    private List<String> address;
    private Phone phone;
}   

通过@Bean的方式进行声明,这里我们加在启动类即可,代码如下

   @Bean
    @ConfigurationProperties(prefix = "com.example.demo")
    public People people() {
        return new People();
    }

此些方式并不需要使用@EnableConfigurationProperties去开启它。

细节:Bean的字段必须有get/set方法,请注意~~~

另外还有一种结合@PropertySource使用的方式,可谓完美搭配

@Component
@PropertySource("classpath:config/object.properties")
@ConfigurationProperties(prefix = "obj")
public class ObjectProperties {}

其余属性见名之意,这里一笔带过:

  • ignoreInvalidFields
  • ignoreNestedProperties
  • ignoreUnknownFields

简单理解:

  • @ConfigurationProperties 是将application配置文件的某类名下所有的属性值,自动封装到实体类中。
  • @Value 是将application配置文件中,所需要的某个属性值,封装到java代码中以供使用。

应用场景不同:

如果只是某个业务中需要获取配置文件中的某项值或者设置具体值,可以使用@Value;

如果一个JavaBean中大量属性值要和配置文件进行映射,可以使用@ConfigurationProperties;

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

(0)

相关推荐

  • Spring boot中PropertySource注解的使用方法详解

    前言 本文将重点讲解一下Spring中@PropertySource注解的使用,如何通过PropertySource注解加载指定的配置文件.以及PropertySource注解与@ConfigurationProperties两个注解的配合使用.下面话不多说了,来随着小编来一起学习学习吧. 1.1. PropertySource注解加载指定的属性文件 Spring框架提供了PropertySource注解,目的是加载指定的属性文件,接下来我们看一下如何使用该注解.首先我们定义一个配置类,并在类中

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

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

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

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

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

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

  • 详解Spring Boot读取配置文件与配置文件优先级

    Spring Boot读取配置文件 1)通过注入ApplicationContext 或者 Environment对象来读取配置文件里的配置信息. package com.ivan.config.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframe

  • SpringBoot 常用读取配置文件的三种方法详解

    目录 前言 一.使用 @Value 读取配置文件 二.使用 @ConfigurationProperties 读取配置文件 1.类上添加@Configuration注解 2.使用@EnableConfigurationProperties注解 3.使用@ConfigurationPropertiesScan扫描 三.使用 Environment 读取配置文件 四.常用的几种数据结构配置读取 我们在SpringBoot框架进行项目开发中该如何优雅的读取配置呢?或者说对于一些List或者Map应该如

  • SpringBoot读取配置文件的五种方法总结

    目录 1.使用 @Value 读取配置文件 2.使用 @ConfigurationProperties 读取配置文件 3.使用 Environment 读取配置文件 4.使用 @PropertySource 读取配置文件 中文乱码 注意事项 5.使用原生方式读取配置文件 总结 Spring Boot 中读取配置文件有以下 5 种方法: 使用 @Value 读取配置文件. 使用 @ConfigurationProperties 读取配置文件. 使用 Environment 读取配置文件. 使用 @

  • springboot读取配置文件中的参数具体步骤

    springBoot是java开发中会经常用到的框架,那么在实际项目中项目配置了springBoot框架,应该如何在项目中读取配置文件中的参数呢? 1.打开eclipse开发工具软件. 2.在项目中确保pom.xml文件已引用了[spring-boot-starter-web]jar包. 因为springBoot启动的时候会自动去获取项目中在resources文件录目下的名为application.properties参数配置文件. 3.在项目中的src/main/resource文件录目下创建

  • SpringBoot如何读取配置文件参数并全局使用

    这篇文章主要介绍了SpringBoot如何读取配置文件参数并全局使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 前言: 读取配置文件参数的方法:@Value("${xx}")注解.但是@Value不能为static变量赋值,而且很多时候我们需要将参数放在一个地方统一管理,而不是每个类都赋值一次. 正文: 注意:一定要给类加上@Component 注解 application.xml test: app_id: 12345 app_

  • @PropertySource 无法读取配置文件的属性值解决方案

    原来Person类这样写: 只写了@PropertySource注解 @Component @PropertySource(value = {"classpath:person.properties"}) public class Person { private String lastName; private int age; private boolean boss; private Date birth; private Map<String,Object> map

  • SpringBoot读取配置文件常用方法解析

    首先回忆一下在没有使用SpringBoot之前也就是传统的spring项目中是如何读取配置文件,通过I/O流读取指定路径的配置文件,然后再去获取指定的配置信息. 传统项目读取配置方式# 读取xml配置文件 public String readFromXml(String xmlPath, String property) { SAXReader reader = new SAXReader(); Document doc = null; try { doc = reader.read(new F

  • 如何在ASP.NET Core类库项目中读取配置文件详解

    前言 最近有朋友问如何在.net core类库中读取配置文件,当时一下蒙了,这个提的多好,我居然不知道,于是这两天了解了相关内容才有此篇文章的出现,正常来讲我们在应用程序目录下有个appsettings.json文件对于相关配置都会放在这个json文件中,但是要是我建立一个类库项目,对于一些配置比如密钥或者其他需要硬编码的数据放在JSON文件中,在.net core之前配置文件为web.config并且有相关的类来读取节点上的数据,现如今在.net core中为json文件,那么我们该如何做?本

  • spring mvc 读取xml文件数据库配置参数的方法

    本文主要介绍怎么通过属性注入与构造器注入实现把我们项目中要用到的数据库参数放到xml文件里面去,方便部署. spring mvc 4.2.6项目 SQL Server 2008数据库 本文介绍的主要使用ApplicationContext以及其实现类实现.主要用到的是ClassPathXmlApplicationContext. ClassPathXmlApplicationContext:从类路径ClassPath中寻找指定的XML配置文件,找到并装载 完成ApplicationContext

随机推荐