Spring Boot 读取配置文件的几种方式

Spring Boot 读取配置文件的方式可以分为
1. 注解
2. 获取 Spring Boot 的环境变量
来获取配置文件的信息,其中注解的方式又有集中表现形式。

第一步:创建 Spring Boot 工程( Maven 工程添加 Spring Boot 相应的依赖)。
这里写图片描述
这里写图片描述
这里写图片描述
现在我们只是测试 Spring Boot 的 配置文件的读取,不需要其他的依赖,所以什么都没选,直接下一步 – 下一步 – 完成,项目目录结构如下:
这里写图片描述
此时的 application.properties 的内容为空
这里写图片描述
POM 文件内容为:

<?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.china.prop</groupId>
    <artifactId>springboot-properties</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-properties</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

POM 文件中的依赖是 IDEA 通过这种创建工程的方式给我们自动生成的。

第二步:在配置文件中添加一些测试信息。
这里写图片描述

string.port=1111
integer.port=1111

db.link.url=jdbc:mysql://localhost:3306/test
db.link.driver=com.mysql.jdbc.Driver
db.link.username=root
db.link.password=root

上面的配置变量仅仅是为了测试而添加的,不具有实际意义。string.port 与 integer.port 都是string 类型普通变量,这里只是做个名称区分而已。

一、 通过获取环境变量来获取配置参数

1.1. 主类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringbootPropertiesApplication {

    public static void main(String[] args) {
        // 获取 Spring Boot 上下文
        ConfigurableApplicationContext ctx = SpringApplication.run(SpringbootPropertiesApplication.class, args);
        // ctx.getEnvironment(); // 获取 边境变量
        System.out.println("===========================================");
        //获取字符串
        System.out.println("String: " + (ctx.getEnvironment().getProperty("string.port") + 1111) );

        //获取整数
        System.out.println("Interger:   " + (ctx.getEnvironment().getProperty("integer.port",Integer.class) + 1111 ));
        System.out.println(ctx.getEnvironment().getProperty("db.link.url"));
        System.out.println(ctx.getEnvironment().getProperty("db.link.driver"));
        System.out.println(ctx.getEnvironment().getProperty("db.link.username"));
        System.out.println(ctx.getEnvironment().getProperty("db.link.password"));
        System.out.println("===========================================");

    }
}

1.2. 运行主类

===========================================
String: 11111111
Interger:   2222
jdbc:mysql://localhost:3306/test
com.mysql.jdbc.Driver
root
root
===========================================

可以看到配置文件中相同格式的port变量,可以获取到不同的格式数据。

  1. 1 新建 bean,通过注入环境变量来获取配置信息。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyConf {

    @Autowired
    private Environment env;

    public void show(){
        System.out.println("===========================================");
        //获取字符串
        System.out.println("String: " +env.getProperty("string.port") + 1111);

        //获取整数
        System.out.println("Interger:   " + (env.getProperty("integer.port",Integer.class) + 1111 ));
        System.out.println(env.getProperty("db.link.url"));
        System.out.println(env.getProperty("db.link.driver"));
        System.out.println(env.getProperty("db.link.username"));
        System.out.println(env.getProperty("db.link.password"));
        System.out.println("===========================================");
    }
}

2.2 改造主类并运行

public static void main(String[] args) {

                ConfigurableApplicationContext ctx = SpringApplication.run(SpringbootPropApplication.class, args);

        MyConf myconf = (MyConf) ctx.getBean("myConf");
        myconf.show();

        ctx.close();
    }

结果:

===========================================
String: 11111111
Interger:   2222
jdbc:mysql://localhost:3306/test
com.mysql.jdbc.Driver
root
root
===========================================

二、通过注解获取配置文件信息

  1. 改造上面的 bean 配置类 MyConf:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyConf {

    @Value("${string.port}")     private int intPort;
    @Value("${string.port}")     private  String stringPort;
    @Value("${db.link.url}")     private String dbUrl;
    @Value("${db.link.driver}")  private String dbDriver;
    @Value("${db.link.username}")private String dbUsername;
    @Value("${db.link.password}")private String dbPassword;

    public void show(){
        System.out.println("===========================================");
        System.out.println("intPort :   " + (intPort + 1111));
        System.out.println("stringPort :   " + (stringPort + 1111));
        System.out.println("string :   " + dbUrl);
        System.out.println("string :   " + dbDriver);
        System.out.println("string :   " + dbUsername);
        System.out.println("string :   " + dbPassword);
        System.out.println("===========================================");
    }
}
  1. 运行主类可得:
===========================================
intPort :   2222
stringPort :   11111111
string :   jdbc:mysql://localhost:3306/test
string :   com.mysql.jdbc.Driver
string :   root
string :   root
===========================================
  1. 指定配置文件,@PropertySource可以声明多个,
    或者使用@PropertySources(@PropertySource(“xxx”),@PropertySource(“xxx”))。
    2.1 新建配置文件 my.prop
aaa.a=111
aaa.b=222
aaa.c=333

2.2 新建配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config/my.prop")
public class PropConf {

    @Value("${aaa.a}")
    private String a;
    @Value("${aaa.b}")
    private String b;
    @Value("${aaa.c}")
    private String c;

    public void show(){
        System.out.println("a --- > " + a);
        System.out.println("b --- > " + b);
        System.out.println("c --- > " + c);
    }
}

2.3. 在主类中添加相应调用代码

PropConf conf = (PropConf) ctx.getBean("propConf");
conf.show();

2.4. 结果:

a --- > 111
b --- > 222
c --- > 333

改造一

可以改造上面的PropConf 类:添加@ConfigurationProperties(prefix = “aaa”)
指定配置文件的前缀,生成giter 和 setter 方法来获取配置信息。


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config/my.prop")
@ConfigurationProperties(prefix = "aaa")
public class PropConf {

    private String a;
    private String b;
    private String c;

    public String getA() {return a;}
    public void setA(String a) {this.a = a;}
    public String getB() {return b;}
    public void setB(String b) {this.b = b;}
    public String getC() {return c;}
    public void setC(String c) {this.c = c;}

    public void show(){
        System.out.println("a --- > " + a);
        System.out.println("b --- > " + b);
        System.out.println("c --- > " + c);
    }
}

运行主类可以获得同样的结果。

改造二

可以只声明 setter 方法:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config/my.prop")
@ConfigurationProperties(prefix = "aaa")
public class PropConf {

    private String a;
    private String b;
    private String c;

    public void setA(String a) {  this.a = a;  }
    public void setB(String b) { this.b = b;  }
    public void setC(String c) {  this.c = c; }

    public void show(){
        System.out.println("a --- > " + a);
        System.out.println("b --- > " + b);
        System.out.println("c --- > " + c);
    }
}

运行主类也可以得到同样的结果:

a --- > 111
b --- > 222
c --- > 333

=======================================

笔记1

上面获取配置文件的位置都是在 classpath 根目录下面的,Spring Boot 默认的配置文件地址有两个:(application.properties 为默认的配置文件名称)
1. classpath: 即放在resources里面。
2. classpath:config里面。
这里写图片描述
3. file:/
4. file:/config/

笔记2

在系统系统时可以通过 –spring.config.name=xxx.properties 环境变量指定配置文件。
比如resources下有一个 dblink.properties,然后添加启动参数:
这里写图片描述

笔记3 应用启动可以指定配置文件地址

这里写图片描述

笔记4 Spring Boot 配置文件可以使用变量

这里写图片描述

笔记5 配置文件可以使用数组或者集合

  1. 在配置文件中添加集合信息
aaa.host[0]=127.0.0.1
aaa.host[1]=10.66.0.108
aaa.host[2]=10.66.0.111
aaa.host[3]=10.66.0.12
aaa.host[4]=10.66.0.134
  1. 在配置类中注入参数
    这里写图片描述
  2. 输出 host变量 可得:
[127.0.0.1, 10.66.0.108, 10.66.0.111, 10.66.0.12, 10.66.0.134]
  • 15
    点赞
  • 122
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
### 回答1: C知道回答:开启 Spring Boot 特性的方式有以下几种: 1. 使用 @EnableAutoConfiguration 注解 2. 使用 @SpringBootApplication 注解 3. 使用 @Configuration 和 @Import 注解手动导入配置类 4. 使用 XML 配置文件手动配置 Spring Boot 特性 ### 回答2: 开启 Spring Boot 特性有以下几种方式: 1. 使用@EnableAutoConfiguration注解:通过在主配置类上添加@EnableAutoConfiguration注解,可以自动开启Spring Boot的自动配置特性。该注解会根据项目中的依赖关系自动配置相应的组件和配置项,简化项目配置工作。 2. 使用@SpringBootApplication注解:@SpringBootApplication是Spring Boot项目的入口注解,它包含了@EnableAutoConfiguration和@Configuration注解。使用@SpringBootApplication注解可以一次性开启Spring Boot的自动配置、组件扫描和配置类的扫描等特性。 3. 使用starter依赖:Spring Boot提供了一系列的starter依赖,每个starter都定义了一组常用的依赖项。通过在项目中引入相应的starter依赖,可以方便地开启特定的功能特性。比如,使用spring-boot-starter-web依赖可以开启Web开发相关的特性。 4. 自定义配置类:在Spring Boot中,我们可以通过编写自定义的配置类来开启一些特定的功能。通过在配置类上使用@Configuration注解,我们可以定义一些@Bean的方法来配置特定的组件或特性。通过将这个配置类注册为Bean,在应用启动时自动生成相应的组件。 综上所述,使用@EnableAutoConfiguration注解、@SpringBootApplication注解、starter依赖和自定义配置类等方式都可以帮助开启Spring Boot的特性。根据项目需求和实际情况,选择适合的方式来快速搭建和配置Spring Boot应用。 ### 回答3: 开启 Spring Boot 特性有以下几种方式: 1. 使用 @EnableAutoConfiguration 注解:Spring Boot 基于约定优于配置的原则,自动配置了很多常用的特性。通过在主配置类上加上 @EnableAutoConfiguration 注解,可以启用自动配置特性。该注解会根据项目使用的依赖自动配置相关的 Bean,简化了配置过程。 2. 配置文件属性:Spring Boot 通过读取配置文件中的属性来设置特性。可以通过在 application.properties 或 application.yml 配置文件中设置相关属性来开启特性。例如,可以设置 spring.data.mongodb.uri 属性来启用 MongoDB 的支持。 3. 使用 @Conditional 注解:Spring Boot 提供了很多条件注解,利用这些注解可以根据条件来选择性地开启特定的特性。例如,可以使用 @ConditionalOnClass 注解来判断某个类是否在 classpath 中存在,从而决定是否启用某个特性。 4. 自定义配置类:Spring Boot 提供了一个 @Configuration 注解,通过在该注解下定义相关的配置类,可以进行更细粒度的配置。在配置类中可以使用 @Bean 注解配置特性相关的 Bean,从而启用特性。 5. 外部化配置:Spring Boot 可以通过外部化配置来灵活地开启和配置特性。可以通过命令行参数、环境变量、属性文件方式来设置特性相关的配置项。 总之,Spring Boot 提供了多种开启特性的方式,开发人员可以根据项目需求和个人偏好选择适合的方式来启用特性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值