• springBoot 读取yml 配置文件的三种方式 (包含以及非component下)


    遇到的问题

    一般spring Boot 环境中可以直接通过 @Value 方式相当于读取注入的方式直接获得配置文件中的值,但实际上当处于非标准的 controller ,service 或 component 注解下的文件想要读取时,由于不是 properties 也不能直接通过properties 的方式直接加载,直接读取文件流也不知道是否可行,查找部分资料后找到了解决方式,下面做下记录

    标准读取方式一(一般controller 以及 service 等包含component 可以直接获取spring 中的值)

    @Value
    即类似于

    @Service
    @Slf4j
    public class AutoTestServiceImpl implements AutoTestService {
    
        @Value("${autotest.server.url}")
        private String baseUrl;
        
        ........
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    application.yml 或者 application.properties 配置文件中如下

    yml

    autotest:
      server:
        url: http://localhost:8080
    
    • 1
    • 2
    • 3

    properties

    autotest.server.url=http://localhost:8080
    
    • 1

    spring的 Environment 类

    SpringBoot 可以使用 @Autowired 注解注入 Environment 对象

    SpringBoot 会将配置文件中所有的数据封装到 Environment 对象中,使用只需要通过调用 Environment 对象的getProperty(String name) 方法即可获取

    例如上面 yml 或 properties 中的值可以通过

    @RestController
    @RequestMapping("/testCon")
    public class BookController {
        
        @Autowired
        private Environment env;
        
        @GetMapping("/{id}")
        public void gettest(@PathVariable Integer id){
            System.out.println(env.getProperty("autotest.server.url"));
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    非标准 controller 或者 service 等文件中无法直接通过 @autowired 方式获取 Environment 时的处理方式

    这里可以直接通过 spring 原有的 ApplicationContext 来获取该对象从而实现从 yml 获取数据,properties 当然也可以,但properties 可以通过直接加载 properties 的方式获取值,相对来说更容易一点

    实例如下:
    这里先要定义一个从 spring环境上下文 获取已放到容器实体的工具类,这个是 一般的spring都支持的,也是常用的工具之一
    工具定义如下:

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    import java.util.Collection;
    
    @Component
    public final class ToolSpring implements ApplicationContextAware {
        private static ApplicationContext applicationContext = null;
    
        public static Object getBean(String name) {
            return getApplicationContext().getBean(name);
        }
    
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        public static <T> T getBean(Class<T> clazz) {
            return getApplicationContext().getBean(clazz);
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if (ToolSpring.applicationContext == null) {
                ToolSpring.applicationContext = applicationContext;
            }
        }
    
        public static <T> Collection<T> getBeansOfType(Class<T> clazz) {
            return applicationContext.getBeansOfType(clazz).values();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    通过 实现 ApplicationContextAware 来获取spring 上下文对象,以此获取容器中的 Bean

    实际使用时一般也用于无法直接通过 @Autowired 或 @Resource 注入的属性,都可以通过这种方式获取,由于 Environment 为springBoot 自身提供的 Bean 故可以获取到
    如下:
    这里我在初始化时通过该方式给予赋值

    public class MyTest  {
    
        private String baseUrl;
    
        {
            Environment bean = ToolSpring.getBean(Environment.class);
            baseUrl = bean.getProperty("autotest.server.url");
        }
    
    	// 此时下面的其他方法即可引用 baseUrl
        .........................
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    但是: 这种通过 Environment 获取数据的方式并不常用,非必要可以不用,毕竟加载了项目配置文件内的所有数据

    自定义对象封装数据

    这种方式没有实际使用过,但也记录一下
    SpringBoot 也提供了将配置文件中的数据封装到自定义实体类对象中的方式

    1. 为了将实体类 bean 的创建交给 Spring 管理 在自定义类上添加 @Component 注解
    2. 使用 @ConfigurationProperties 注解表示加载配置文件,在该注解中也可以使用 prefix 属性指定只加载指定前缀的数据
    3. 在需要使用该类的controller, Service等中进行注入

    例如:

    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Data
    @Component
    @ConfigurationProperties(prefix = "auto.message")
    public class WxTemplateProperties {
      private String id;
      private String akId;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    如果没有使用过 lombok 的 @Data 可以手动引入一下,效果仅仅是自动生成 get set 方法,如果不需要也可以手动生成 get set 有快捷键也很容易。

    如果
    添加 @ConfigurationProperties 出现警告,则可以添加依赖

    		<dependency>
    			<groupId>org.springframework.bootgroupId>
    			<artifactId>spring-boot-configuration-processorartifactId>
    			<optional>trueoptional>
    		dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    解决

    之后改类可以通过 @Autowired 等方式注入后使用。

  • 相关阅读:
    c高级 day1
    文件上传 [GXYCTF2019]BabyUpload1
    HTML页面获取URL传递的参数值
    Casbin之Model模型存储(动态初始化)、Model模型存储(字符串加载)
    基于粒子群优化算法、鲸鱼算法、改进的淘沙骆驼模型算法(PSO/SSA/tGSSA)的微电网优化调度(Matlab代码实现)
    vscode插件开发(三)命令
    MT4选网页版还是桌面版?anzo capital昂首资本分析优劣
    7.2-CM46 合法括号序列判断
    mysql索引
    Web APIs Web APIs第七天
  • 原文地址:https://blog.csdn.net/weixin_44131922/article/details/126866040