SpringBoot 读取配置文件的4种方式

配置文件

server:
  port: 8080
  servlet:
    context-path: /elasticsearch

spring:
  application:
    name: elasticsearch

1 使用@Value注解

在类中使用@Value注解来注入配置值

package com.xu.test;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringBootTests {

	@Value("${spring.application.name}")
	private String name;

	@Test
	public void test() {
		System.out.println(name);
	}

}
elasticsearch

2 使用@ConfigurationProperties注解

创建一个Java Bean类,并使用@ConfigurationProperties注解指定配置文件的前缀,然后Spring Boot会自动将配置值注入到该Bean中。

package com.xu.test.conf;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author hyacinth
 */
@Data
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class MyConf {

    private String host;

    private String port;

    private String password;

    private String timeout;

}
package com.xu.test;

import cn.hutool.json.JSONUtil;
import com.xu.test.conf.MyConf;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringBootTests {
	
    @Autowired
    private MyConf conf;

    @Test
    public void test() {
        System.out.println(JSONUtil.toJsonPrettyStr(conf));
    }

}
{
    "host": "127.0.0.1",
    "port": "6379",
    "password": null,
    "timeout": "10000"
}

3 使用Environment

package com.xu.test;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;

@SpringBootTest
class SpringBootTests {

    @Autowired
    private Environment env;

    @Test
    public void test() {
        System.out.println(env.getProperty("spring.application.name"));
    }

}
elasticsearch

4 使用@PropertySource注解

如果有其他的配置文件,需要在配置类上使用@PropertySource注解指定配置文件的路径,然后通过@Value注解或Environment接口来读取配置值(@PropertySource只支持properties文件)。

4.0 new.yml

test:
  name: "测试配置文件"

4.1 @PropertySource 支持 yml/yaml 文件

package com.xu.test.conf;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;
import java.util.Properties;

/**
 * @author hyacinth
 */
public class YamlConfigFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        name = (name != null) ? name : resource.getResource().getFilename();
        if (StrUtil.isBlank(name)) {
            throw new RuntimeException("配置文件不存在!");
        }
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(name, new Properties());
        } else if (StrUtil.containsAnyIgnoreCase(name, ".yml", ".yaml")) {
            Properties yml = loadYml(resource);
            return new PropertiesPropertySource(name, yml);
        } else {
            return new ResourcePropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

}

4.2 使用@PropertySource注解

package com.xu.test.conf;


import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;

/**
 * @author hyacinth
 */
@Data
@Component
@PropertySource(value = "classpath:new.yml", factory = YamlConfigFactory.class)
public class MyConf {

    @Value("${test.name}")
    private String name;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}
package com.xu.test;

import cn.hutool.json.JSONUtil;
import com.xu.test.conf.MyConf;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringBootTests {

    @Autowired
    private MyConf conf;

    @Test
    public void test() {
        System.out.println(JSONUtil.toJsonPrettyStr(conf));
    }

}
{
    "name": "测试配置文件"
}

5 读取数组

server:
  port: 8080
  servlet:
    context-path: /elasticsearch

spring:
  application:
    name: elasticsearch

phone: 123123123,
  3123123,
  312312312,
  35345345,
package com.xu.test;

import cn.hutool.core.collection.CollUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringBootTests {

    @Value("#{'${phone}'.replaceAll(' ', '').split(',')}")
    private List<String> phone;

    @Test
    public void test1() {
        System.out.println(phone);
    }

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot项目中,可以通过在`application.properties`或`application.yml`配置文件中定义配置属性,然后在项目启动时使用`@Value`注解注入属性值来读取配置文件数据。 以`application.properties`为例,首先在`src/main/resources`目录下创建该文件,并定义需要读取的配置属性,例如: ```properties # 数据库连接配置 spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password ``` 然后在需要使用该配置属性的类中使用`@Value`注解注入属性值,例如: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class DatabaseConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; // getters and setters } ``` 在上面的代码中,通过在`@Value`注解中使用`${}`来引用配置属性,然后将属性值注入到对应的变量中。 需要注意的是,使用`@Value`注解注入属性值的类必须是Spring Bean,因此需要在类上添加`@Component`注解或其它符合条件的注解,以便Spring能够扫描并创建该类的实例。同时,需要在Spring Boot应用程序的入口类上添加`@EnableConfigurationProperties`注解,以启用注入属性值的功能。 另外,如果需要读取`application.yml`配置文件中的属性值,可以使用类似的方式,并在`@Value`注解中使用`:`来引用属性,例如: ```yaml # 数据库连接配置 spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: password ``` ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class DatabaseConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; // getters and setters } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值