• springboot读取自定义properties配置文件方法


    1. 添加pom.xml依赖

    <!-- springboot configuration依赖 -->
    <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId> spring-boot-configuration-processor</artifactId>
          <optional> true </optional>
    </dependency>

    2. 在resources下建一个config包(当然包名随意), 在包里建一个remote.properties(老规矩, 文件名随意)

     3. 在配置文件中写入测试内容

    remote.testname=张三
    remote.testpass=123456

    4. 写一个实体类, 属性和配置文件对应

    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.stereotype.Component;
    
    @Configuration
    @ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
    @PropertySource("classpath:config/remote.properties")
    @Data
    @Component
    public class RemoteProperties {
        private String testname;
        private int testpass;
    }

    5. 在调用配置文件信息的类中搞事情

    @EnableConfigurationProperties(RemoteProperties.class)
    @RestController
    public class PageTestController {
    
        @Autowired
        RemoteProperties remoteProperties;
    
        @RequestMapping("testProperties")
        public String testProperties(){
            String str = remoteProperties.getTestname();
            int i = remoteProperties.getTestpass();
            System.out.println(str);
            System.out.println(i);
            return str+i;
        }
    }

    PS: 有的小伙伴获取的配置文件出现了中文乱码问题, 请点击下方链接

    解决 springboot 读取 properties 中文乱码

  • 相关阅读:
    Linux終端一行命令发送邮件
    团队冲刺2.4
    团队冲刺2.3
    团队冲刺2.2
    找水王
    评价win10自带输入法——微软拼音输入法
    梦断代码阅读笔记01
    团队冲刺2.1
    第十三周总结
    第十二周总结
  • 原文地址:https://www.cnblogs.com/zhainan-blog/p/11460615.html
Copyright © 2020-2023  润新知