Spring读取配置获取配置yml文件的 3 种方法

yml配置文件

spring:
  cache:
    type: jcache
    jcache:
      config: classpath:ehcache.xml
  datasource:
    name: 乳腺健康检测系统
    本地数据库
    url: jdbc:mysql://127.0.0.1:3306/breast?&rewriteBatchedStatements=true
    username: root
    password: root

1:使用 @Value 读取配置文件(适用于参数少的情况)

我们可以直接在对象的属性上使用 @Value 注解,同时以 ${} 的形式传入配置文件中对应的属性。
同时需要在该类的上方使用 @Configuration 注解,将该类作为配置文件加入,在启动项目的时候实现注入。

@Configuration
public class DatasourceProperties {
    @Value("${spring.datasource.url}")
    private String datasourceUrl;
    @Value("${spring.datasource.username}")
    private String datasourceUsername;
    @Value("${spring.datasource.password}")
    private String datasourcePassword;
}

2:使用 @ConfigurationProperties 读取配置文件(适用于参数多的情况,不需要在每一个字段的上面的使用@Value注解)

//@ConfigurationProperties注解声明当前类为配置读取类
//prefix="spring.datasource" 表示读取前缀为spring.datasource的属性
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DatasourceProperties {

    private String datasourceUrl;

    private String datasourceUsername;

    private String datasourcePassword;
}

注意:
1:必须保证属性名称和字段一模一样,且类需要提供字段的setter,getter方法
2:如果仅仅只是使用了@ConfigurationProperties注解是没有效果的,它并不会将这个配置注入容器中,它还需要和注入容器的注解一起使用,例如@Configuration,也可以是@Controller、@RestController、@Service、@Componet等注解,加入到Ioc容器里

使用@ConfigurationPropertiesScan扫描特定包下所有的被@ConfigurationProperties标记的配置类(没有加其他注解注入容器的时候,例如@Configuration,也可以是@Controller、@RestController、@Service、@Componet等注解),并将它们进行IoC注入

@ConfigurationPropertiesScan
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

3:使用 Environment 读取配置文件

Environment 是 Spring Core 中的一个用于读取配置文件的类,将此类使用 @Autowired 注入到类中就可以使用它的 getProperty 方法来获取某个配置项的值

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
class MainApplicationTests {
	@Resource
    private Environment environment;

    @Test
    public void testOrder() {
        String names=environment.getProperty("spring.datasource.names");
        System.out.println(names);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值