关于@PropertySource配置的用法解析

目录
  • @PropertySource配置用法
    • 功能
    • 源码
    • 使用示例
    • 示例测试
  • @PropertySource注解
    • 例如
    • 示例

@PropertySource配置用法

功能

加载指定的属性文件(*.properties)到 Spring 的 Environment 中。可以配合 @Value 和@ConfigurationProperties 使用。

@PropertySource 和 @Value组合使用,可以将自定义属性文件中的属性变量值注入到当前类的使用@Value注解的成员变量中。

@PropertySource 和 @ConfigurationProperties组合使用,可以将属性文件与一个Java类绑定,将属性文件中的变量值注入到该Java类的成员变量中。

源码

package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.io.support.PropertySourceFactory;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    /**
     * 属性源的名称
     */
    String name() default "";
    /**
     * 属性文件的存放路径
     */
    String[] value();
    /**
     * 如果指定的属性源不存在,是否要忽略这个错误
     */
    boolean ignoreResourceNotFound() default false;
    /**
     * 属性源的编码格式
     */
    String encoding() default "";
    /**
     * 属性源工厂
     */
    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}

使用示例

属性文件:demo.properties

demo.name=huang
demo.sex=1
demo.type=demo

示例一:@PropertySource + @Value

package com.huang.pims.demo.props;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = {"demo/props/demo.properties"})
public class ReadByPropertySourceAndValue {
    @Value("${demo.name}")
    private String name;
    @Value("${demo.sex}")
    private int sex;
    @Value("${demo.type}")
    private String type;
    @Override
    public String toString() {
        return "ReadByPropertySourceAndValue{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", type='" + type + '\'' +
                '}';
    }
}

示例二:@PropertySource 和 @ConfigurationProperties

package com.huang.pims.demo.props;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = {"demo/props/demo.properties"})
@ConfigurationProperties(prefix = "demo")
public class ReadByPropertySourceAndConfProperties {
    private String name;
    private int sex;
    private String type;
    public void setName(String name) {
        this.name = name;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getName() {
        return name;
    }
    public int getSex() {
        return sex;
    }
    public String getType() {
        return type;
    }
    @Override
    public String toString() {
        return "ReadByPropertySourceAndConfProperties{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", type='" + type + '\'' +
                '}';
    }
}

示例测试

package com.huang.pims.demo.runners;
import com.huang.pims.demo.props.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class OutputPropsRunner implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(OutputPropsRunner.class);
    @Autowired
    private ReadByPropertySourceAndValue readByPropertySourceAndValue;
    @Autowired
    private ReadByPropertySourceAndConfProperties readByPropertySourceAndConfProperties;
    @Override
    public void run(String... args) throws Exception {
        LOGGER.info(readByPropertySourceAndValue.toString());
        LOGGER.info(readByPropertySourceAndConfProperties.toString());
    }
}

启动项目即可看到效果。

从截图中可以看出,需要读取的属性配置,都已经成功读取出来了。

@PropertySource注解

@PropertySource是Spring boot为了方便引入properties配置文件提供的一个注解,可以标注在SpringBoot的启动类上,还可以标注在配置类(使用@Configuration标注的类)上。

例如

@PropertySource(value = {"classpath:box.properties"})

将classpath下的box.properties,注入到Spring环境中,使用@Value("${key}")取值。

示例

box.properties文件:

# 工具箱配置 
preserveFilePath=/box/webserver/uploadfile/preservefile/

注入:

@SpringBootApplication
@PropertySource(value = {"classpath:box.properties"})
public class ToolboxApiApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ToolboxApiApplication.class, args);
    } 
}

取值:

@RestController
public class DeleteFileController {
    @Value("${preserveFilePath}")
    private String preserveFilePath;
 
    @GetMapping("/deleteFile")
    public void test(){
        System.out.println(preserveFilePath);
    }
}

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

(0)

相关推荐

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

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

  • @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

  • spring @Profiles和@PropertySource实现根据环境切换配置文件

    目录 @Profiles和@PropertySource根据环境切换配置文件 利用spring.profiles.active=@spring.active@不同环境下灵活切换配置文件 一.创建配置文件 二.POM文件添加PROFILES配置 三.具体应用 @Profiles和@PropertySource根据环境切换配置文件 使用@PropertySource注解加载配置文件,并制定解析配置文件的解析器默认是properties,可以自己指定使用Yml配置文件解析器. @SpringBootA

  • 关于@PropertySource配置的用法解析

    目录 @PropertySource配置用法 功能 源码 使用示例 示例测试 @PropertySource注解 例如 示例 @PropertySource配置用法 功能 加载指定的属性文件(*.properties)到 Spring 的 Environment 中.可以配合 @Value 和@ConfigurationProperties 使用. @PropertySource 和 @Value组合使用,可以将自定义属性文件中的属性变量值注入到当前类的使用@Value注解的成员变量中. @Pr

  • Log4j日志记录框架配置及用法解析

    任何一个系统都需要日志记录功能,以便开发调试,线上环境追溯问题. 常用的日志记录框架Log4j.其是apache的一个开源日志组件. #生产环境使用info #log4j.rootLogger = info,stdout,logfile #开发环境使用debug log4j.rootLogger = info,stdout,logfile log4j.logger.com.seecen.system.aop.advice = trace,aop log4j.appender.stdout = o

  • Spring interceptor拦截器配置及用法解析

    fifter.servlet.interceptor fifter用来处理请求头.请求参数.编码的一些设置,然后转交给servlet,处理业务,返回 servlet现在常用的spring,servlet拦截/到DispatcherServlet,交由spring管理 interceptor,servlet请求之后可以实现HandlerInterceptor做到preHandle.postHandle.afterCompletion在controller之前.之后.渲染之后 登陆 业务中常用的登陆

  • Python3中configparser模块读写ini文件并解析配置的用法详解

    Python3中configparser模块简介 configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近.Python2.x 中名为 ConfigParser,3.x 已更名小写,并加入了一些新功能. 配置文件的格式如下: [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User =

  • SpringCloud配置刷新原理解析

    我们知道在SpringCloud中,当配置变更时,我们通过访问http://xxxx/refresh,可以在不启动服务的情况下获取最新的配置,那么它是如何做到的呢,当我们更改数据库配置并刷新后,如何能获取最新的数据源对象呢?下面我们看SpringCloud如何做到的. 一.环境变化 1.1.关于ContextRefresher 当我们访问/refresh时,会被RefreshEndpoint类所处理.我们来看源代码: /* * Copyright 2013-2014 the original a

  • Python openpyxl模块原理及用法解析

    这篇文章主要介绍了Python openpyxl模块原理及用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 此模块不是Python内置的模块需要安装,安装方法如下 pip install openpyxl 注意: 此模块只支持offce 2010,即是电子表格后缀是*.xlsx 1.openpyxl模块常用函数 import openpyxl wb = openpyxl.load_workbook('example.xlsx') ####

  • SpringBoot扩展外部化配置的原理解析

    Environment实现原理 在基于SpringBoot开发的应用中,我们常常会在application.properties.application-xxx.properties.application.yml.application-xxx.yml等配置文件中设置一些属性值,然后通过@Value.@ConfigurationProperties等注解获取,或者采用编码的方式通过Environment获取. # application.properties my.config.appId=d

  • mysql having用法解析

    having的用法 having字句可以让我们筛选成组后的各种数据,where字句在聚合前先筛选记录,也就是说作用在group by和having字句前.而 having子句在聚合后对组记录进行筛选. SQL实例: 一.显示每个地区的总人口数和总面积. SELECT region, SUM(population), SUM(area) FROM bbc GROUP BY region 先以region把返回记录分成多个组,这就是GROUP BY的字面含义.分完组后,然后用聚合函数对每组中 的不同

  • sql中的 where 、group by 和 having 用法解析

    废话不多说了,直接给大家贴代码了,具体代码如下所示: --sql中的 where .group by 和 having 用法解析 --如果要用到group by 一般用到的就是"每这个字" 例如说明现在有一个这样的表:每个部门有多少人 就要用到分组的技术 select DepartmentID as '部门名称',COUNT(*) as '个数' from BasicDepartment group by DepartmentID --这个就是使用了group by +字段 进行了分组

  • Java Thread多线程详解及用法解析

    最全面的java多线程用法解析,如果你对Java的多线程机制并没有深入的研究,那么本文可以帮助你更透彻地理解Java多线程的原理以及使用方法. 1.创建线程 在Java中创建线程有两种方法:使用Thread类和使用Runnable接口.在使用Runnable接口时需要建立一个Thread实例.因此,无论是通过Thread类还是Runnable接口建立线程,都必须建立Thread类或它的子类的实例.Thread构造函数: public Thread( ); public Thread(Runnab

随机推荐