Springboot如何读取配置文件中的属性

Springboot自定义属性注入

SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.yml(application.yaml)进行配置。

SpringBoot默认会从resources目录下加载application.properties或application.yml(application.yaml)文件

下面介绍如何获取配置文件中的属性

我们以自定义数据源为例,以application.yml为默认配置文件,有如下配置:

jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/test
  username: root
  password: root

一、使用注解@Value映射

@Configuration
public class JdbcConfig {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

如上代码,可以通过@Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上,会自动为字段赋值

二、使用注解@ConfigurationProperties映射

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

@ConfigurationProperties注解声明当前类为配置读取类

prefix="jdbc"表示读取前缀为jdbc的属性

会将配置文件中前缀为prefix的属性赋给类中同名的字段

注意:必须保证属性名称和字段一模一样,且类需要提供字段的setter方法

我们还可以在Spring中使用这个配置读取类,通过@EnableConfigurationProperties注解可以将指定的配置读取类的对象加载到Spring容器

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
    @Autowired
    private JdbcProperties prop;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(prop.getDriverClassName());
        dataSource.setUrl(prop.getUrl());
        dataSource.setUsername(prop.getUsername());
        dataSource.setPassword(prop.getPassword());
        return dataSource;
    }
}

如上,将JdbcProperties的对象加载到容器后,就可以通过@Autowired注解进行注入。

也可以通过构造方法注入:

private JdbcProperties prop;
public JdbcConfig(Jdbcproperties prop){
    this.prop = prop;
}

还有一种方式也可以直接使用配置读取类:

@Bean
public DataSource dataSource(JdbcProperties prop){
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(prop.getDriverClassName());
    dataSource.setUrl(prop.getUrl());
    dataSource.setUsername(prop.getUsername());
    dataSource.setPassword(prop.getPassword());
    return dataSource;
}

这种方式不需要@Autowired注入字段,也不需要构造函数注入,直接在方法中定义配置读取类的形参,Springboot在创建DataSource对象时会自动注入JdbcProperties对象

三、极简的注入方式

@Configuration
public class JdbcConfig {
    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource(){
        return new DruidDataSource();
    }
}

我们直接把@ConfigurationProperties(prefix = "jdbc")声明在需要使用的@Bean的方法上,Springboot会自动将配置文件中以prefix开头的属性赋给要创建对象的类的同名字段上,使用前提:要求类该类必须提供了setter方法

使用profiles实现配置文件的切换

在微服务的开发过程中,我们经常会对不同的环境准备一个配置文件,即使没有多种环境,起码也会分开发环境和生成环境,下面就介绍一下实际开发过程中如何对配置文件进行切换

一、配置多个不同环境的配置文件

如下图:

application-dev和application-prod分别是开发环境和生成环境下使用的配置文件,文件名必须按照“application-xxx”的规则,在application.yml中如下配置进行切换:

application.yml:

spring:
  profiles:
    active: dev

二、一个配置文件中配置多种环境的配置

直接在application.yml中配置:

spring:
  profiles:
    active: dev #选择使用的环境
---
spring:
  profiles: dev #开发环境
jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/dev
  username: root
  password: root

---
spring:
  profiles: prod #生产环境
jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/prod
  username: root
  password: root

不同的环境用“---”进行分割,每种环境使用spring.profiles定义名称

原文地址:https://www.cnblogs.com/ithushuai/p/12656464.html

时间: 2024-08-26 18:14:11

Springboot如何读取配置文件中的属性的相关文章

开发路程(6):Web.config配置文件中的属性add,key,value含义

这是添加自定义字符串的方式,保存是以键-值的形式保存的,可以通过key获取value,一般用这种方法配置全局内使用的字符串. <configuration>是配置文件的根配置节. <appSettings>是自定义配置节,包含自定义应用程序设置. add元素是向应用程序设置集合添加名称/值对形式的自定义应用程序设置. 代码: Web.config 1 <configuration> 2 <appSettings> 3 <add key=”UserNam

applicationContext配置文件中的属性说明

lazy-init:设置只对scop属性为singleton的bean起作用. 1.true:延迟加载:这时在第一次向容器通过getBean索取bean时实例化的. 2.false:表示spring启动是立即进行实例化: 在容器层次中通过在<beans/>元素上使用'default-lazy-init'属性来控制延迟初始化也是可能的.如下面的配置: <beans default-lazy-init="true"><!-- no beans will be

Spring中Bean的作用域、Spring的自动注入、在spring配置文件中引入属性文件

1. Bean的作用域 Bean的作用域默认为单例模式. 2. 自动注入 3. 在spring配置文件中引入属性文件 Bean的作用域默认为单例模式. 原文地址:https://www.cnblogs.com/mcl2238973568/p/11478426.html

java.util.Properties 读取配置文件中的参数

用法 getProperty方法的返回值是String类型. java.util.Properties 读取配置文件中的参数 //读取配置文件 FileInputStream inStream = null; try { inStream = new FileInputStream("/fetchedfile/redis.conf"); Properties prop = new Properties(); prop.load(inStream); Field field; Strin

【SpringBoot】【3】读取配置文件中的参数并配置给全局使用

前言: 读取配置文件参数的方法:@Value("${xx}")注解.但是@Value不能为static变量赋值,而且很多时候我们需要将参数放在一个地方统一管理,而不是每个类都赋值一次. 正文: 注意:一定要给类加上@Component 注解 application.xml test: app_id: 12345 app_secret: 66666 is_active: true 统一读取配置文件参数: package com.example.demo.config; import or

spring整合velocity 配置文件中的属性

spring整合velocity 配置文件中的相关属性 1 <bean id= "viewResolver" class= "org.springframework.web.servlet.view.velocity.VelocityViewResolver" > 2 <!-- 是否缓存模板 --> 3 <property name ="cache" value="false" /> 4 5

读取配置文件中数据库设置信息来创建connection对象

package com.atguigu.jdbc; import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.Driver;import java.sql.SQLException;import java.util.Properties; import org.junit.Test; public class JDBCTest { /** * 编写一个通用的方法

java后台读取配置文件中key与value -----demo

public class ResourcesUtils { /* * @description:根据属性获取文件名 * * @param:propertyName文件的属性名 * * @return:返回文件的属性值 * */ public static String getByName( String propertyName) { String resultM = "";//返回结果 ResourceBundle bundle = ResourceBundle.getBundle(

intellij idea springboot无法读取配置文件的解决方法

问题描述 Spring Boot项目中运行之后,出现如下的错误: *************************** APPLICATION FAILED TO START *************************** Description: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. Reaso