zoukankan      html  css  js  c++  java
  • [spring] @PropertySource

    配置文件

    @PropertySources注解用于加载配置文件到Spring的环境中。

    配置文件如下。

    demo.msg=this is a message.
    

    如何引用到配置文件

    在app项目中,我们通过@PropertySource注解到JavaConfig类上,设置.properties配置文件的路径。

    在gradle项目中,配置文件放在src/main/resources/路径下,还可以放在这个目录下的文件夹。如:src/main/resources/demo/app.properties的设置@PropertySource("demo/app.properties")

    在web项目中,spring web已经将配置文件设置好了,不需要@PropertySource配置。

    如何使用配置的值

    spring里的许多配置可以在.properties文件中直接配置到。

    我们在xml配置,注解等地方需要使用到配置文件的值时,可以使用spring EL语言设置,格式如${x.y.z}

    @PropertySource + @Value

    通过在类上设置@PropertySource设置配置文件。

    通过在成员变量上设置@Value指定所设置在配置文件中的值。

    package com.yww;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    @Component
    @PropertySource(value = "application.properties")
    public class Message {
    
        @Value("${demo.msg}")
        private String msg;
    
    }
    

    @PropertySource + @ConfigurationProperties

    通过在类上设置@PropertySource设置配置文件。

    在类上设置@ConfigurationProperties自动将配置文件中名称满足的配置值设置。

    package com.yww;
    
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    @Component
    @PropertySource(value = "application.properties")
    @ConfigurationProperties(prefix = "demo")
    public class Message {
    
        private String msg;
    
    }
    

    @ConfigurationPropertiesspring boot中的类,需要导入相应的库。

    参考

    https://www.cnblogs.com/517cn/p/10946213.html

  • 相关阅读:
    正则表达式
    Java 枚举(enum) 详解7种常见的用法
    【20170921】(Unfinished)2017暑假北京学习 day 2
    (Unfinished)2017暑假北京学习 day 2
    Openjudge NOI题库 数论4975 两只鼹鼠
    Openjudge NOI题库 数论185 反正切函数的应用
    Noip1998 提高组3 卢斯加法表
    【自己的小玩具程序】化学方程式配平【测试中】【未完成】
    Code Vs 1010 过河卒
    NOI 练手题 图像旋转翻转变换
  • 原文地址:https://www.cnblogs.com/maplesnow/p/11625983.html
Copyright © 2011-2022 走看看