• (005)Spring Boot之读取配置文件


      (一)配置文件中取值

      springboot的默认配置文件是application.properties或者application.yml。读取配置文件有以下两种方式

      1、注入Environment对象,用Environment对象获取

      2、使用Value注解

      获取的值默认都是字符串类型,使用Value注解时,自动转化类型,使用Environment对象时,指定类,如下:

      pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.edu.spring</groupId>
        <artifactId>springboot</artifactId>
        <version>1.0.0</version>
        <packaging>jar</packaging>
    
        <name>springboot</name>
        <!-- FIXME change it to the project's website -->
        <url>http://www.example.com</url>
        
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-dependencies</artifactId>
                    <version>2.1.6.RELEASE</version>
                    <scope>import</scope>
                    <type>pom</type>
                </dependency>
            </dependencies>
        </dependencyManagement>
        
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
        </dependencies>
    
    </project>
    View Code

      UserConfig.java

    package com.edu.spring.springboot;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.env.Environment;
    import org.springframework.stereotype.Component;
    
    @Component
    public class UserConfig {
    
        @Autowired
        private Environment environment;
        
        @Value("${local.port}")
        private String port;
        
        @Value("${local.port}")
        private Integer port2;
        
        public void show(){
            System.out.println("local.ip= "+environment.getProperty("local.ip"));
            System.out.println("local.port= "+environment.getProperty("local.port",Integer.class));
            System.out.println("local.port= "+port);
            System.out.println("local.port= "+port2);
        }
    }
    View Code

      App.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class App 
    {
        public static void main( String[] args )
        {
            
            ConfigurableApplicationContext context=SpringApplication.run(App.class, args);
            System.out.println(context.getEnvironment().getProperty("local.ip"));
            context.getBean(UserConfig.class).show();
            context.close();
        }
    }
    View Code

      运行结果如下:

       假如在配置文件中没对应的属性,取值的时候可以指定默认值,即配置文件中存在属性,取配置文件中的,否则取指定的。如下:

      UserConfig.java

    package com.edu.spring.springboot;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.env.Environment;
    import org.springframework.stereotype.Component;
    
    @Component
    public class UserConfig {
    
        @Autowired
        private Environment environment;
        
        @Value("${name:你好}")
        private String name;
        
        public void show(){
            System.out.println("name= "+environment.getProperty("name","你好"));
            System.out.println("name= "+name);
        }
    }
    View Code

      App.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class App 
    {
        public static void main( String[] args )
        {
            
            ConfigurableApplicationContext context=SpringApplication.run(App.class, args);
            context.getBean(UserConfig.class).show();
            context.close();
        }
    }
    View Code

      运行结果如下:

       springboot的默认配置文件可以放在classpath、classpath:/config、file、file:/config下面(file可以是任意名字),如下图所示:

       (二)读取指定的配置文件

      1、使用@PropertySource指定配置文件路径和名称,该注解可以多次使用,如下:

      配置文件共4个

      application.properties内容:url4=jdbc:mysql:localhost:3306/springboot4

      jdbc.properties内容:url1=jdbc:mysql:localhost:3306/springboot1

      jdbc2.properties内容:url2=jdbc:mysql:localhost:3306/springboot2

      jdbc3.properties内容:url3=jdbc:mysql:localhost:3306/springboot3

      FileConfig.java

    package com.edu.spring.springboot;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    @Configuration
    @PropertySource("classpath:jdbc.properties")
    @PropertySource("classpath:jdbc2/jdbc2.properties")
    @PropertySource("file:/d:/1_1test/jdbc3.properties")
    public class FileConfig {
    
    }
    View Code

      JdbcConfig.java

    package com.edu.spring.springboot;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    public class JdbcConfig {
    
        @Value("${url1}")
        private String url1;
        
        @Value("${url2}")
        private String url2;
        
        @Value("${url3}")
        private String url3;
        
        @Value("${url4}")
        private String url4;
        
        public void show(){
            System.out.println("url1: "+url1);
            System.out.println("url2: "+url2);
            System.out.println("url3: "+url3);
            System.out.println("url4: "+url4);
        }
    }
    View Code

      App.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class App 
    {
        public static void main( String[] args )
        {
            ConfigurableApplicationContext context=SpringApplication.run(App.class, args);
            context.getBean(JdbcConfig.class).show();
            context.close();
        }
    }
    View Code

      运行结果如下:

       2、使用@PropertySources一次指定所有的配置文件

      FileConfig.java

    package com.edu.spring.springboot;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.annotation.PropertySources;
    
    @Configuration
    @PropertySources({@PropertySource("classpath:jdbc.properties"),@PropertySource("classpath:jdbc2/jdbc2.properties"),
                      @PropertySource("file:/d:/1_1test/jdbc3.properties")})
    public class FileConfig {
    
    }
    View Code

      运行结果如下:

       (三)自动配置文件中的前缀

      使用@ConfigurationProperties注解中的属性prefix或者value可以指定属性的前缀,结合属性的set方法可以取到配置文件中的属性值,如下:

      application.properties

    ds.url=jdbc:mysql:localhost:3306/springboot;
    ds.driverClassName=com.mysql.jdbc.Driver;
    ds.username=asdf;
    ds.password=123456;
    View Code

      DataSourceProperties.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(value="ds")
    public class DataSourceProperties {
    
        private String url;
        
        private String driverClassName;
        
        private String username;
        
        private String password;
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public void setDriverClassName(String driverClassName) {
            this.driverClassName = driverClassName;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
        
        public void show(){
            System.out.println("--------------DataSourceProperties---------------");
            System.out.println("ds.url: "+url);
            System.out.println("ds.driverClassName: "+driverClassName);
            System.out.println("ds.username: "+username);
            System.out.println("ds.password: "+password);
        }
        
        
    }
    View Code

      App.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class App 
    {
        public static void main( String[] args )
        {
            ConfigurableApplicationContext context=SpringApplication.run(App.class, args);
            context.getBean(DataSourceProperties.class).show();
            context.close();
        }
    }
    View Code

      运行结果如下:

       (四)读取数组或者集合

      application.properties

    ds.hosts[0]=192.168.1.100
    ds.hosts[1]=192.168.1.101
    ds.hosts[2]=192.168.1.102
    
    ds.sports[0]=8080
    ds.sports[1]=8081
    ds.sports[2]=8082
    ds.sports[3]=8083
    View Code

      TomcatProperties.java

    package com.edu.spring.springboot;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties("ds")
    public class TomcatProperties {
    
        private List<String> hosts=new ArrayList<String>();
        private String[] sports;
    
        public void setHosts(List<String> hosts) {
            this.hosts = hosts;
        }
    
        public void setSports(String[] sports) {
            this.sports = sports;
        }
    
        @Override
        public String toString() {
            return "TomcatProperties [hosts=" + hosts + ",sports="+Arrays.asList(sports)+"]";
        }
    
    }
    View Code

      App.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class App 
    {
        public static void main( String[] args )
        {
            ConfigurableApplicationContext context=SpringApplication.run(App.class, args);
            System.out.println(context.getBean(TomcatProperties.class));
            context.close();
        }
    }
    View Code

      运行结果如下:

       (四)启动时指定不同的配置文件

      resources中有三个配置文件,如下图所示:

       application.properties中内容:url=mysql:jdbc://127.0.0.1/db_springboot

      application-test.properties中内容:url=mysql:jdbc://127.0.0.1/db_springboot_test

      application-dev.properties中内容:url=mysql:jdbc://127.0.0.1/db_springboot_dev

      App.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class App 
    {
        public static void main( String[] args )
        {
            SpringApplication app=new SpringApplication(App.class);
            app.setAdditionalProfiles("test");
            ConfigurableApplicationContext context=app.run(args);
            System.out.println(context.getEnvironment().getProperty("url"));
            context.close();
        }
    }
    View Code

      运行结果如下:

      如果代码中的"test"修改为"dev",则读取application-dev.properties中的url属性

      如果注释掉代码中的app.setAdditionalProfiles行,则读取application.properties中的url属性

      app.setAdditionalProfiles可以指定多个文件,如下:

      添加配置文件application-aa.properties,内容是:name=hello application-aa.properties

      App.java

    package com.edu.spring.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class App 
    {
        public static void main( String[] args )
        {
            SpringApplication app=new SpringApplication(App.class);
            app.setAdditionalProfiles("dev","test","aa");
            ConfigurableApplicationContext context=app.run(args);
            System.out.println(context.getEnvironment().getProperty("url"));
            System.out.println(context.getEnvironment().getProperty("name"));
            context.close();
        }
    }
    View Code

      运行结果如下:

       备注:同时加载多个配置文件,且文件中有相同的属性时,则取后加载的,如同时加载了"dev"与"test",则取"test"中的url。

      

      

  • 相关阅读:
    CARTA:持续自适应风险与信任评估
    Quantitative Finance Reading List
    金融是不是一群不事生产的人,对社会毫无贡献的人,互相对赌的零和游戏?
    青藤云安全细述最具影响力的三大安全架构:零信任、ATT&CK、自适应安全
    以太坊DApp开发指南
    开源 serverless 产品原理剖析(一)
    Top 5 decentralized platforms
    Top 5 decentralized platforms
    区块链上编程:DApp 开发简介
    说说期货高频的一些分类
  • 原文地址:https://www.cnblogs.com/javasl/p/11827832.html
Copyright © 2020-2023  润新知