关于@PropertySource配置的用法解析

 更新时间:2022年03月25日 11:16:41   作者:马尔斯的蓝色  
这篇文章主要介绍了关于@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);
    }
}

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

相关文章

  • SpringCloud feign服务熔断下的异常处理操作

    SpringCloud feign服务熔断下的异常处理操作

    这篇文章主要介绍了SpringCloud feign服务熔断下的异常处理操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • FluentMybatis实现mybatis动态sql拼装和fluent api语法

    FluentMybatis实现mybatis动态sql拼装和fluent api语法

    本文主要介绍了FluentMybatis实现mybatis动态sql拼装和fluent api语法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • Java中的反射机制基本运用详解

    Java中的反射机制基本运用详解

    这篇文章主要介绍了Java 反射机制原理与用法,结合实例形式详细分析了Java反射机制的相关概念、原理、基本使用方法及操作注意事项,需要的朋友可以参考下
    2021-08-08
  • Spring MVC 拦截器实现代码

    Spring MVC 拦截器实现代码

    本篇文章主要介绍了Spring MVC 拦截器的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-02-02
  • Java Hibernate中使用HQL语句进行数据库查询的要点解析

    Java Hibernate中使用HQL语句进行数据库查询的要点解析

    HQL是Hibernate框架中提供的关系型数据库操作脚本,当然我们也可以使用原生的SQL语句,这里我们来看一下在Java Hibernate中使用HQL语句进行数据库查询的要点解析:
    2016-06-06
  • Spring Data JPA 建立表的联合主键

    Spring Data JPA 建立表的联合主键

    这篇文章主要介绍了Spring Data JPA 建立表的联合主键。本文详细的介绍了2种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-04-04
  • 浅谈Java 中的单元测试

    浅谈Java 中的单元测试

    这篇文章主要介绍了Java 中的单元测试的相关资料,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2020-09-09
  • Java后台生成图片的完整步骤

    Java后台生成图片的完整步骤

    在一些详情页面中,可能需要对上传到服务器中的图片生成以缩略图的形式展示,这篇文章主要给大家介绍了关于Java后台生成图片的相关资料,需要的朋友可以参考下
    2021-08-08
  • mybatis-plus分页无效问题解决

    mybatis-plus分页无效问题解决

    本文主要介绍了mybatis-plus分页无效问题解决,原因是配置分页插件的版本问题,旧版本和新版本的MyBatis-Plus需要不同的分页配置,感兴趣的可以了解一下
    2025-03-03
  • Java停止线程的3种方法

    Java停止线程的3种方法

    这篇文章主要分享Java停止线程的3种方法,分别是自定义中断标识符,停止线程、使用线程中断方法interrupt停止线程、使用stop停止线程。下文详细介绍需要的小伙伴可以参考一下
    2022-05-05

最新评论