广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring详解四种加载配置项的方法
  • 690
分享到

Spring详解四种加载配置项的方法

2024-04-02 19:04:59 690人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录1.spring加载yml文件2.spring 加载 properties 文件3.spring加载系统磁盘(properties)文件4.spring加载xml文件5.Java

本文默认 spring 版本是 spring5

1 spring 加载 yml 文件

2 spring 加载 properties 文件

3 spring 加载 系统磁盘 文件

4 spring 加载 xml 文件

5 Java 基于 InputStream 读取 properties 配置文件

spring框架默认加载配置:

resources 下的文件名称为application的 application.yml 以及 application.properties, 默认会被spring加载到容器 Container

中,如果他们有重复的配置项,会被默认合并,并且 application.properties优先级更高. 下面的 LoadYmlTest.java 有详细解释

示例:

# application.yml 
user:
  userName: ifredom_name
  age: 30  # 定义了属性 age

# application.properties 
# 也定义了属性 age
user.age=99
user.sex=2

package com.example.commonmybatisplus.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Data
@Configuration
@ConfigurationProperties(prefix = "user")
public class LoadPropertySourceYmlConfig {
    private String userName;
    private int sex;
    private int age;
}
package com.example.commonmybatisplus.PropertySourceTest;
import com.example.commonmybatisplus.config.LoadPropertySourceYmlConfig;
import com.example.commonmybatisplus.entity.UserEntity;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;

@SpringBootTest
public class LoadYmlTest {
    @Autowired
    private LoadPropertySourceYmlConfig ymlConfig;
    @Test
    public void testYml() {
        String name = ymlConfig.getUserName();
        int sex = ymlConfig.getSex();
        int age = ymlConfig.getAge();
        System.out.println(name); // ifredom
        System.out.println(sex);  // 2
        System.out.println(age);  // 99
    }
}

1.spring加载yml文件

上面已经通过默认的方式演示了如何加载默认的application.yml,但是更好的写法是,将我们自定义的配置独立为一个单独的文件。

比如我们开发微信公众号,小程序开发时,就需要用到配置,此时的配置就应该独立为一个额外的文件。(此处将演示加载为 List)

一共有3步:

  • 创建配置文件 wechat-config.yml
  • 定义配置类 LoadPropertySourceYmlConfig,用来加载yml中的数据 (指定配置类的加载器) (因为 spring 配置类的默认加载器是 PropertiesLoader加载器,所以我们需要自定义 yml加载器。可以自行查看注解 @PropertySource 源码
  • 自定义配置类加载器 YamlSourceFactory,继承Spring提供的默认配置类构造器 DefaultPropertySourceFactory
  • 测试

示例:

# main/resources/chat-config.yml

#微信小程序的appid
appid: app-xxx
#微信小程序的Secret
secret: secretxxx
#微信小程序消息服务器配置的token
token: token-xxx
#微信小程序消息服务器配置的EncodingAESKey
aesKey: aesKey-xxx

wx:
  configs:
    #微信小程序的appid
    - appid: app1
      #微信小程序的Secret
      secret: secret1
      #微信小程序消息服务器配置的token
      token: token1
      #微信小程序消息服务器配置的EncodingAESKey
      aesKey: aesKey1

      #微信小程序的appid
    - appid: appid2
      #微信小程序的Secret
      secret: secret2
      #微信小程序消息服务器配置的token
      token: token2
      #微信小程序消息服务器配置的EncodingAESKey
      aesKey: aesKey2

def-my-var1: 定义配置属性var1
def-my-var2: 定义配置属性var2

这里需要注意,在上面的配置文件中是 wx.configs, 因此在配置类中,也必须用同名的 configs 来接收

package com.example.commonmybatisplus.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.stereotype.Component;
import java.util.List;

@Data
@Configuration
@PropertySource(value = "classpath:wechat-config.yml", factory = YamlSourceFactory.class)
@ConfigurationProperties(prefix = "wx")
public class LoadPropertySourceYmlConfig {
    private List<Config> configs;
    @Data
    public static class Config {
        private String appid;
        private String secret;
        private String token;
        private String aesKey;
    }
    private String appid;
    private String secret;
    private String token;
    private String aesKey;
}
// 自定义记载器
package com.example.commonmybatisplus.config;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
import java.util.List;
public class YamlSourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        // 这里使用Yaml配置加载类来读取yml文件信息
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}

测试结果

package com.example.commonmybatisplus.PropertySourceTest;
import com.example.commonmybatisplus.config.LoadPropertySourceYmlConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;

@SpringBootTest
public class LoadYmlTest {
    @Autowired
    private LoadPropertySourceYmlConfig ymlConfig;
    @Test
    public void testYml() {
        String appidXXX = ymlConfig.getAppid();
        String secretXXX = ymlConfig.getSecret();
        System.out.println("单独的属性配置---appidXXX: " + appidXXX);
        System.out.println("单独的属性配置---secretXXX: " + secretXXX);
        // 以下演示 配置项作为 List
        List<LoadPropertySourceYmlConfig.Config> configs = ymlConfig.getConfigs();
        // 迭代 List 每一项
        for (LoadPropertySourceYmlConfig.Config config : configs) {
            System.out.println("属性作为List: " + config);
        }
        // 获取List种的某一项
        LoadPropertySourceYmlConfig.Config configFirst = configs.get(0);
        String appidFirst = configFirst.getAppid();
        System.out.println("List的第一项: " + configFirst);
        System.out.println("List的第一项的其中一个属性: " + appidFirst);
        LoadPropertySourceYmlConfig.Config configSecond = configs.get(1);
        String secretSecond = configSecond.getSecret();
        System.out.println("List的第二项: " + configSecond);
        System.out.println("List的第二项的其中一个属性: " + secretSecond);
    }
}

2.spring 加载 properties 文件

从上一步我们已经知道了, spring 默认使用 properties 文件的加载器。因此,我们可以少一步构造加载器

  • 创建配置文件 alibaba-config.properties
  • 定义配置类 LoadPropertySourceConfig,用来加载yml中的数据
  • 测试

# main/resources/alibaba-config.properties
ali-yun.username="ifredom"
ali-yun.passWord="123456"
ali-yun.blog="Http://www.ifredom.com"

package com.example.commonmybatisplus.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Data
@Configuration
@PropertySource("classpath:alibaba-config.properties")
@ConfigurationProperties(prefix = "aliyun")
public class LoadPropertySourceConfig {
    private String username;
    private String password;
    private String blog;
}

测试:

package com.example.commonmybatisplus.PropertySourceTest;
import com.example.commonmybatisplus.config.LoadPropertySourceConfig;
import com.example.commonmybatisplus.config.LoadPropertySourceYmlConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;

@SpringBootTest
public class LoadYmlTest {
    @Autowired
    private LoadPropertySourceYmlConfig ymlConfig;
    @Autowired
    private LoadPropertySourceConfig propertyConfig;
    @Test
    public void testProperty() {
        String username = propertyConfig.getUsername();
        String password = propertyConfig.getPassword();
        String blog = propertyConfig.getBlog();
        System.out.println("单独的属性配置---username: " + username);
        System.out.println("单独的属性配置---password: " + password);
        System.out.println("单独的属性配置---blog: " + blog);
    }
    @Test
    public void testYml() {
    }
}

细心的同学应该发现了,在配置文件中定义的是ali-yun中间明明有一个短横线,读取属性的时候怎么没了?

这是因为 Spring 配置加载器类对诸如 空格,下划线,短横线,大小写都做了替空处理,也就是:配置文件是不分大小写的; 并且 下划线,短横线也会忽略: user_name -> username, pass-word -> password.因此取名你可以很随意

3.spring加载系统磁盘(properties)文件

有时候我们会需要加载其他项目下的数据库,而配置文件并不在当前项目路劲下,因此需要指定文件路径。

  • 磁盘路径可以是相对路径,绝对路径,也可以通过系统属性值指定变量
  • 相对路径,文件在应用根目录下:@PropertySource(value = {"file:project1.properties"})
  • 相对路径,文件在应用根目录下:@PropertySource(value = {"file:./project1.properties"})
  • 绝对路径,在指定的路径下:@PropertySource(value = {"file:D:\\project\\project1.properties"})
  • 通过系统属性值指定变量:@PropertySource(value = {"file:${user.dir}/project1.properties"})

由于加载xml文件还需要对xml文件进行解析,此处不做讲解。仅仅使用 properties 文件做例子。 示例:

#  位于D盘下的配置文件 D:\project1.properties
driverClassName=com.Mysql.cj.jdbc.Driver
url="https://www.ifredom.com"
username="ifredom"
password="123456"

由于配置文件没有前缀,因此 配置类 必须使用@Value()进行映射

package com.example.commonmybatisplus.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Data
@Configuration
@PropertySource(value = {"file:D:\\project1.properties"})
public class LoadDiskConfig {
    @Value("driverClassName")
    private String driverClassName;
    @Value("url")
    private String url;
    @Value("username")
    private String username;
    @Value("password")
    private String password;
}

@SpringBootTest
public class LoadYmlTest {
    @Autowired
    private LoadDiskConfig diskConfig;
    @Test
    public void testDisk() {
        String username = diskConfig.getUsername();
        String url = diskConfig.getUrl();
        System.out.println(username);
        System.out.println(url);
    }
}

4.spring加载xml文件

  • 创建一个xml文件:applicationContext.xml,并在其中定义一个bean
  • 通过 ApplicationContext 来加载读取xml文件

不再推介使用 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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd ">
    <bean id="blog" name="author" class="com.example.commonmybatisplus.entity.UserEntity">
        <property name="id" value="1"/>
        <property name="name" value="ifredom"/>
        <property name="age" value="30"/>
    </bean>
</beans>
@Data
public class UserEntity {
    private Long id;
    private String name;
    private int sex;
    private int age;
}
@SpringBootTest
public class LoadYmlTest {
    @Test
    public void testXml() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserEntity author = context.getBean("author", UserEntity.class);
        System.out.println(author.getName());
    }
}

5.Java基于InputStream读取properties配置文件

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
@SpringBootTest
public class LoadYmlTest {
    @Test
    public void testInputStream() throws IOException {
        Properties properties = new Properties();
        // 使用InPutStream流读取properties文件
        BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/project1.properties"));
        properties.load(bufferedReader);
        // 获取key对应的value值
        String driverClassName = properties.getProperty("driverClassName");
        String username = properties.getProperty("username");
        System.out.println(driverClassName);
        System.out.println(username);
    }
}

到此这篇关于Spring详解四种加载配置项的方法的文章就介绍到这了,更多相关Spring加载配置项内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring详解四种加载配置项的方法

本文链接: https://www.lsjlt.com/news/152246.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring详解四种加载配置项的方法
    目录1.spring加载yml文件2.spring 加载 properties 文件3.spring加载系统磁盘(properties)文件4.spring加载xml文件5.Java...
    99+
    2022-11-13
  • Spring加载加密的配置文件详解
    本文实例为大家分享了Spring加载加密的配置文件,供大家参考,具体内容如下一、继承并实现自己的属性文件配置器类public class EncryptPropertyPlaceholderConfigurer extends Proper...
    99+
    2023-05-31
    spring 加载 加密
  • 详解Spring获取配置的三种方式
    目录前言Spring中获取配置的三种方式通过@Value动态获取单个配置通过@ConfigurationProperties+前缀方式批量获取通过Environment动态获取单个配...
    99+
    2022-11-13
  • 详解利用Spring加载Properties配置文件
    记得之前写Web项目的时候配置文件的读取都是用Properties这个类完成的,当时为了项目的代码的统一也就没做什么改动。但事后一直在琢磨SpringMVC会不会都配置的注解功能了?经过最近的研究返现SpringMVC确实带有这一项功能,S...
    99+
    2023-05-31
    spring 加载 properties
  • Spring Boot配置多数据源的四种方式
    1、导读 在日常开发中我们都是以单个数据库进行开发,在小型项目中是完全能够满足需求的。 但是,当我们牵扯到像淘宝、京东这样的大型项目的时候,单个数据库就难以承受用户的CRUD操作。 那么此时,我们就需要使用多个数据源进行读写分离的操作,这种...
    99+
    2023-08-20
    spring boot java 数据库 mybatis 后端
  • Spring实例化bean的四种方式详解
    目录一、bean实例化——构造方法(常用)二、bean实例化——静态工厂(了解)三、bean实例化——实例工厂...
    99+
    2022-11-13
  • SpringBoot配置文件加载方法详细讲解
    目录配置文件的读取顺序多坏境的配置文件个性化配置自定义配置文件名称和路径加载yml文件配置文件的读取顺序 根目录/config/application.properties根目录/c...
    99+
    2022-11-13
    SpringBoot配置文件导入 SpringBoot配置加载 SpringBoot加载配置文件
  • mybatis 加载配置文件的方法(两种方式)
    一. 使用sqlSessionFactory 的 mapperLocations 进行加载,<!-- SessionFactory --> <bean id="sqlSessionFactory" class="org....
    99+
    2023-05-30
    mybatis 配置文件
  • Vue项目中打包优化的四种方法详解
    目录前言打包优化的目的:性能优化的主要方向:1.异步组件配置(路由懒加载)2.去掉打包后的 console3.使用CDN4.yarn build生成dist目录总结前言 默认情况下,...
    99+
    2022-11-13
  • 基于Python实现配置热加载的方法详解
    目录背景如何实现使用多进程实现配置热加载使用signal信号量来实现热加载采用multiprocessing.Event 来实现配置热加载结语背景 由于最近工作需求,需要在...
    99+
    2022-11-11
  • Spring注解配置IOC,DI的方法详解
    目录1、注解 @Component第一步:在 applicationContext.xml 中引入命名空间第二步:在 applicationContext.xml 文件中引...
    99+
    2022-11-13
  • Spring事务Transaction配置的五种注入方式详解
    前段时间对spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识。通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的。总结如下:Spring配置文件中关于事务...
    99+
    2023-05-31
    spring 注入 ct
  • Android更新UI的四种方法详解
    前言 相信每位Android开发者们都知道更新UI只能在主线程中进行,若是在子线程执行任务后需要更新UI,则需要借助handler跳转到主线程中。以下介绍几种操作UI的方法。 ...
    99+
    2022-06-06
    方法 Android
  • 关于Spring配置文件加载方式变化引发的异常详解
    目录问题背景过程定位根因配置加载顺序解决问题背景 我们项目的配置文件一直是通过Apollo进行管理,但是近期由于某些特殊的部署需求,需要使用K8S的原生对象来获取配置,如此一来的话,...
    99+
    2022-11-12
  • Django加载配置的过程详解
    目录一. Django服务启动 manage.py二. 引入配置三. 加载配置一. Django服务启动 manage.py os.environ.setdefault("DJANG...
    99+
    2022-11-11
  • spring中aop的xml配置方法实例详解
    前言AOP:即面向切面编程,是一种编程思想,OOP的延续。在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等等。aop,面向切面编程的目标就是分离关注点,比如:一个骑士只需要关注守护安全,或者远征,而骑士辉煌一生的事迹由谁...
    99+
    2023-05-31
    spring aop xml配置
  • 详解Java停止线程的四种方法
    一、线程停止基础知识 interrupted(): 测试当前线程是否已经中断。该方法为静态方法,调用后会返回boolean值。不过调用之后会改变线程的状态,如果是中断状态...
    99+
    2022-11-12
  • Spring注解@Value及属性加载配置文件方式
    Spring中使用@Value注解给bean加载属性的配置文件有两种使用方式 第一种:使用@Value("#{configProperties['websit.msgname']}"...
    99+
    2022-11-12
  • Spring Boot两种全局配置和两种注解的操作方法
    目录零、学习目标 一、全局配置文件概述二、Application.properties配置文件1、配置tomcat端口号和web虚拟路径2、对象类型的配置与使用3、两种属性...
    99+
    2022-11-12
  • win7查看电脑配置的四种简单方法
    1. 使用系统信息工具:在开始菜单中搜索"系统信息",打开系统信息窗口,在窗口左侧的导航栏中选择"系统汇总",可以查看到电脑的基本配...
    99+
    2023-08-21
    win7
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作