zoukankan      html  css  js  c++  java
  • 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 中文乱码

  • 相关阅读:
    洛谷P3811题解
    洛谷P3353在你窗外闪耀的星星-题解
    Map根据value来排序
    java8 groupby count
    Java反射
    maven profile环境切换
    获取nginx代理情况下的真实ip
    获取request里header的name和value
    git 删除iml文件
    java list 排序
  • 原文地址:https://www.cnblogs.com/zhainan-blog/p/11460615.html
Copyright © 2011-2022 走看看