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 中文乱码

  • 相关阅读:
    列表第一篇文档与其他文档不同样式
    当前栏目判断有无子栏目
    当前栏目文章数
    有关当前焦点的标签,只有我能理解
    给推荐一个标识
    附件下载次数
    收藏代码
    关联会员头像信息
    当前三级折叠菜单导航
    centos7 安装配置apache
  • 原文地址:https://www.cnblogs.com/zhainan-blog/p/11460615.html
Copyright © 2011-2022 走看看