• SpringBoot获取配置的几种方式


    一、引入依赖

    <!-- 核心启动器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    二、application.properties

    server.port=9080
    user.username=lin@j
    user.age=20

     三、读取配置信息的几种方式

    1. 利用@PropertySource获取resource目录下的资源,Environment获取属性

    @Component
    @PropertySource(value = {"classpath:application.properties"})
    public class PropertiesConfigOne {
    
        @Autowired
        private Environment environment;
    
        public void printProperties(){
            String userName = environment.getProperty("user.username");
            System.out.println("user.username:" + userName);
            String age = environment.getProperty("user.age");
            System.out.println("user.age:" + age);
        }
    }

    2. 利用@PropertySource获取resource目录下的资源,@ConfigurationProperties找到该资源的前缀, 通过getter、setter方法注入及获取配置

    @Component
    @PropertySource(value = {"classpath:application.properties"})
    @ConfigurationProperties(prefix = "user")
    public class PropertiesConfigTwo {
    
        //属性上不用使用@Value("${username}"), 这样会报错的
        private String username;
        private Integer age;
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public void printProperties(){
            System.out.println("username:" + username);
            System.out.println("age:" + age);
        }
    
    }

    3. 利用PropertiesLoaderUtil加载配置文件

    @Component
    public class PropertiesConfigThree {
    
        public void printProperties() throws IOException {
            //PropertiesLoaderUtils是spring-core提供的
            Properties properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
            System.out.println("user.username:" + properties.getProperty("user.username"));
            System.out.println("user.age:" + properties.getProperty("user.age"));
        }
    }
  • 相关阅读:
    【MySQL】查看数据库所占空间大小
    Redis 和 Memcached 有什么区别?Redis 的线程模型是什么?为什么单线程的 Redis 比多线程的 Memcached 效率要高得多?
    Hbase 大表快速count
    redis击穿,穿透,雪崩以及解决方案
    elasticsearch和lucene的关系以及elasticsearch的核心概念
    Java 序列化 之 Serializable
    win10+virtualBox(CentOS7)java 环境搭建之 mysql8安装
    win10+virtualBox(CentOS7)java 环境搭建之 jdk 1.8安装
    win10+virtualBox(CentOS7)java 环境搭建之 网络设置
    joplin for Arch Linux
  • 原文地址:https://www.cnblogs.com/myitnews/p/12356730.html
Copyright © 2020-2023  润新知