SpringBoot自定义加载yml实现方式,附源码解读

作者:九州暮云 时间:2022-01-22 22:39:40 

自定义加载yml,附源码解读

昨天在对公司的微服务配置文件标准化的过程中,发现将原来的properties文件转为yml文件之后,微服务module中标记有@Configuration的配置类都不能正常工作了,究其原因,是由于@PropertySource属性默认只用于标记并告诉spring boot加载properties类型的文件

spring boot 2.0.0.RELEASE版的文档解释如下:

24.6.4 YAML Shortcomings

YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.

这段话的意思是说:

24.6.4 YAML 缺点

YAML 文件不能用 @PropertySource 注解来标记加载。因此,在需要加载值的场景,你需要使用属性文件。

解决方法

解决这个问题并不难,我们只需要自定义一个yaml文件加载类,并在@PropertySource注解的factory属性中声明就可以。scala版实现代码如下,spring boot版本为2.0.0.RELEASE:

1、自定义yaml文件资源加载类 

import org.springframework.boot.env.YamlPropertySourceLoader
import org.springframework.core.env.PropertySource
import org.springframework.core.io.support.{DefaultPropertySourceFactory, EncodedResource}
/**
  * yaml资源加载类
  */
class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory{
  override def createPropertySource(name: String, resource: EncodedResource): PropertySource[_] = {
    if (resource == null) {
      super.createPropertySource(name, resource)
    }
    return new YamlPropertySourceLoader().load(resource.getResource.getFilename, resource.getResource, null)
  }
}

这个类继承自DefaultPropertySourceFactory类,并重写了createPropertySource方法。

2、引入@PropertySource注解并使用

import com.core.conf.YamlPropertyLoaderFactory
import javax.persistence.EntityManagerFactory
import javax.sql.DataSource
import org.springframework.beans.factory.annotation.{Autowired, Qualifier}
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder
import org.springframework.context.annotation.{Bean, Configuration, PropertySource}
import org.springframework.core.env.Environment
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.orm.jpa.{JpaTransactionManager, LocalContainerEntityManagerFactoryBean}
import org.springframework.transaction.PlatformTransactionManager
/**
  * JPA 数据源配置
  */
@Configuration
@PropertySource(value = Array("classpath:/bootstrap-report.yml"), factory = classOf[YamlPropertyLoaderFactory])
@EnableJpaRepositories(
  entityManagerFactoryRef = "reportEntityManager",
  transactionManagerRef = "reportTransactionManager",
  basePackages = Array("com.report.dao")
)
class ReportDBConfig {
  @Autowired
  private var env: Environment = _
  @Bean
  @ConfigurationProperties(prefix = "spring.datasource.report")
  def reportDataSource(): DataSource = DataSourceBuilder.create.build
  @Bean(name = Array("reportEntityManager"))
  def reportEntityManagerFactory(builder: EntityManagerFactoryBuilder): LocalContainerEntityManagerFactoryBean = {
    val entityManager = builder
      .dataSource(reportDataSource())
      .packages("com.report.model") //设置JPA实体包路径
      .persistenceUnit("reportPU")
      .build
    entityManager.setJpaProperties(additionalProperties())
    entityManager
  }
  @Bean(name = Array("reportTransactionManager"))
  def reportTransactionManager(@Qualifier("reportEntityManager")
                               entityManagerFactory: EntityManagerFactory): PlatformTransactionManager = {
    new JpaTransactionManager(entityManagerFactory)
  }
  /**
    * 获取JPA配置
    *
    * @return
    */
  def additionalProperties(): Properties = {
    val properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.report.hibernate.ddl-auto"))
    properties.setProperty("hibernate.show_sql", env.getProperty("spring.jpa.report.show-sql"))
    properties.setProperty("hibernate.dialect", env.getProperty("spring.jpa.report.database-platform"))
    properties
  }
}

源码解读

实现该功能涉及两个地方:

1、@PropertySource注解:用于声明和配置自定义配置类需要加载的配置文件信息,源码及属性解释如下:

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;
}

2、spring boot配置文件解析类:

在@PropertySource注解的定义中,属性factory主要用来声明解析配置文件的类,这个类必须是PropertySourceFactory接口的实现,在我们自定义了yaml文件加载类之后,它的实现关系如下:

SpringBoot自定义加载yml实现方式,附源码解读

从以上类图可以发现,它的实现类主要有2个:

  • DefaultPropertySourceFactory:默认的配置文件解析类,主要用于解析properties配置文件

  • YamlPropertyLoaderFactory:自定义的yaml资源解析类,主要用于解析yaml配置文件,使用时需要在PropertySource注解的factory属性上声明

这两个类将配置文件解析后,会将属性信息存入Spring的Environment对象中,以供我们通过@Value注解等方式使用。

因此,我们如果遇到spring boot不能加载并解析自定义配置的时候,可以试试自定义配置文件解析类解决。

参考链接

YAML Shortcomings

Exposing YAML as Properties in the Spring Environment

ConfigurationProperties loading list from YML:base on kotlin

Properties转YAML idea插件&mdash;&mdash;生产力保证:Properties to YAML Converter

如何引入多个yml方法

SpringBoot默认加载的是application.yml文件,所以想要引入其他配置的yml文件,就要在application.yml中激活该文件

定义一个application-resources.yml文件(注意:必须以application-开头)

application.yml中:

spring: 
 profiles:
   active: resources

以上操作,xml自定义文件加载完成,接下来进行注入。

application-resources.yml配置文件代码:

user:
 filepath: 12346
 uname: "13"
admin:
 aname: 26

方案一:无前缀,使用@Value注解

@Component
//@ConfigurationProperties(prefix = "user")
public class User {
    @Value("${user.filepath}")
    private String filepath;
    @Value("${user.uname}")
    private String uname;
   public String getFilepath() {
       return filepath;
   }
   public void setFilepath(String filepath) {
       this.filepath = filepath;
   }
   public String getUname() {
       return uname;
   }
   public void setUname(String uname) {
       this.uname = uname;
   }
   @Override
   public String toString() {
       return "User{" +
               "filepath='" + filepath + '\'' +
               ", uname='" + uname + '\'' +
               '}';
   }
}

方案二:有前缀,无需@Value注解

@Component
@ConfigurationProperties(prefix = "user")
public class User {
    //@Value("${user.filepath}")
    private String filepath;
    //@Value("${user.uname}")
    private String uname;
   public String getFilepath() {
       return filepath;
   }
   public void setFilepath(String filepath) {
       this.filepath = filepath;
   }
   public String getUname() {
       return uname;
   }
   public void setUname(String uname) {
       this.uname = uname;
   }
   @Override
   public String toString() {
       return "User{" +
               "filepath='" + filepath + '\'' +
               ", uname='" + uname + '\'' +
               '}';
   }
}

测试类:

package com.sun123.springboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UTest {
   @Autowired
   User user;
   @Test
   public void test01(){
       System.out.println(user);
   }
}

测试结果:

SpringBoot自定义加载yml实现方式,附源码解读

来源:https://my.oschina.net/dabird/blog/1795007

标签:SpringBoot,加载yml,源码
0
投稿

猜你喜欢

  • 使用JMX连接JVM实现过程详解

    2022-07-25 23:05:45
  • 使用JSON.toJSONString格式化成json字符串时保留null属性

    2023-05-10 14:56:34
  • Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用详解

    2021-08-01 19:27:32
  • 修改idea的这些启动参数,令你的idea健步如飞

    2021-11-14 14:48:11
  • java中重写equals()方法的同时要重写hashcode()方法(详解)

    2022-03-07 22:29:20
  • Spring整合Junit的使用详解

    2022-11-20 18:33:17
  • SpringCloud如何创建一个服务提供者provider

    2023-08-01 01:56:33
  • Spring Boot插件spring tool suite安装及使用详解

    2021-12-15 03:29:23
  • C# Cache缓存读取的设置方法

    2022-11-18 05:33:53
  • C#实现记事本查找与替换功能

    2022-03-24 00:20:58
  • 详细图解Java中字符串的初始化

    2023-11-20 19:34:24
  • Java使用Tess4J实现图像识别方式

    2022-10-07 19:24:11
  • jvm虚拟机类加载机制详解

    2021-10-21 08:33:28
  • 用java WebSocket做一个聊天室

    2021-11-30 00:39:55
  • eclipse实现ElGamal数字签名

    2023-11-26 07:52:47
  • Java并发编程示例(一):线程的创建和执行

    2022-01-24 16:43:49
  • Java中的静态内部类详解及代码示例

    2021-11-25 08:50:00
  • Spring Cloud整合XXL-Job的示例代码

    2021-06-09 06:01:59
  • springboot注册bean的三种方法

    2023-11-22 21:57:12
  • struts2自定义拦截器的示例代码

    2021-12-01 16:24:52
  • asp之家 软件编程 m.aspxhome.com