SpringBoot读取自定义配置文件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot读取自定义配置文件

zhanhjxxx   2022-09-27 我要评论

一、读取系统配置文件application.yaml

1、application.yaml配置文件中增加一下测试配置

testdata:
  animal:
    lastName: 动物
    age: 18
    boss: true
    birth: 2022/02/22
    maps: {key1:value1,key2:value2}
    list: [dog,cat,house]
    dog:
      name: 旺财
      age: 3

2、新建entity实体类Animal

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component//标识为Bean
@ConfigurationProperties(prefix = "testdata.animal")//prefix前缀需要和yml配置文件里的匹配。
@Data//这个是一个lombok注解,用于生成getter&setter方法
public class Animal {
    private String lastName;
    private int age;
    private boolean boss;
    private Date birth;
    private Map<String,String> maps;
    private List<String> list;
    private Dog dog;
}

3、新建entity实体类dog

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.stereotype.Component;
@Component//标识为Bean
@Data//这个是一个lombok注解,用于生成getter&setter方法
@Configuration//标识是一个配置类
public class Dog {
    private String name;
    private int age;
}

4、新建测试类MyTest

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//让测试运行于Spring测试环境
@SpringBootTest(classes = DemoApplication.class)//指定启动类
@EnableConfigurationProperties(RemoteProperties.class)//使RemoteProperties注解类生效
public class MyTests {
    @Autowired
    Animal animal;
    @Test
    public void test2() {
        System.out.println("person===="+animal);
        System.out.println("age======="+animal.getAge());
        System.out.println("dog.name======="+animal.getDog().getName()+" dog.age===="+animal.getDog().getAge());
    }
}

5、运行结果:

二、读取自定义配置文件properties格式内容

1、resources\config目录下新建remote.properties配置文件,内容如下:

remote.testname=张三
remote.testpass=123456
remote.testvalue=ceshishuju

2、新建entity实体类RemoteProperties

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration//表明这是一个配置类
@ConfigurationProperties(prefix = "remote",ignoreInvalidFields = false)//该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的“remote”,ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。
@PropertySource(value="classpath:config/remote.properties",ignoreResourceNotFound = false)//配置文件路径
@Data//这个是一个lombok注解,用于生成getter&setter方法
@Component//标识为Bean
public class RemoteProperties {
    private String testname;
    private String testpass;
    private String testvalue;
}

3、新建测试类MyTests

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//让测试运行于Spring测试环境
@SpringBootTest(classes = DemoApplication.class)//指定启动类
@EnableConfigurationProperties(RemoteProperties.class)//应用配置文件类,使RemoteProperties注解类生效
public class MyTests {
    @Autowired
    RemoteProperties remoteProperties;
    @Test
    public void test2() {
        TestCase.assertEquals(1, 1);
        String testpass=remoteProperties.getTestpass();
        System.out.println("-----------:"+testpass);
        System.out.println("------------:"+remoteProperties.getTestvalue());
    }
}

4、运行结果:

三、读取自定义配置文件yaml格式内容

1、resources\config目录下新建remote.yaml配置文件,内容如下:

remote:
  person:
    testname: 张三
    testpass: 123456
    testvalue: kkvalue

2、新建工厂转换类PropertySourceFactory

package com.example.demo.db.config;
import org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
//把自定义配置文件.yml的读取方式变成跟application.yml的读取方式一致的 xx.xx.xx
public class MyPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        return new YamlPropertySourceLoader().load(name,encodedResource.getResource()).get(0);
    }
}

3、新建entity实体类RemoteProperties

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration//表明这是一个配置类
@ConfigurationProperties(prefix = "remote",ignoreInvalidFields = false)//该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的“remote”,ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。
@PropertySource(value="classpath:config/remote.yaml",factory = MyPropertySourceFactory.class)//配置文件路径,配置转换类
@Data//这个是一个lombok注解,用于生成getter&setter方法
@Component//标识为Bean
public class RemoteProperties {
    @Value("${remote.person.testname}")//根据配置文件写全路径
    private String testname;
    @Value("${remote.person.testpass}")
    private String testpass;
    @Value("${remote.person.testvalue}")
    private String testvalue;
 
}

4、新建测试类MyTests

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//让测试运行于Spring测试环境
@SpringBootTest(classes = DemoApplication.class)//指定启动类
@EnableConfigurationProperties(RemoteProperties.class)//使RemoteProperties注解类生效
public class MyTests {
    @Autowired
    RemoteProperties remoteProperties;
    @Test
    public void test2() {
        TestCase.assertEquals(1, 1);
        String testpass=remoteProperties.getTestpass();
        System.out.println("asdfasdf"+testpass);
        System.out.println("asdfasdf"+remoteProperties.getTestvalue());
    }
}

5、运行结果:

 说明:

 这里需要写一个工厂去读取propertySource(在调试的时候我看到默认读取的方式是xx.xx.xx而自定义的yml配置文件是每一个xx都是分开的,所以不能获取到,而自己创建的配置类MyPropertySourceFactory就是需要把自定义配置文件.yml的读取方式变成跟application的读取方式一致的 xx.xx.xx,并且通过@Value注解指定变量的的关系和yaml配置文件对应)

四、其他扩展内容

可以加入依赖spring-boot-configuration-processor后续写配置文件就有提示信息:

<!-- 导入文件处理器,加上这个,以后编写配置就有提示了-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId> spring-boot-configuration-processor</artifactId>
    <optional> true </optional>
</dependency>

其他获取配置相关内容后续更新。

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们