常见的springboot读取配置文件的方式

 application.properties配置文件部分配置

这里简单使用application.properties配置文件部分配置举例,配置如下:

profile.name= test
profile.age= 18

@Value读取一个配置项

@SpringBootApplication
public class TestApplication implements InitializingBean {
    @Value("${profile.name}")
    private String name;

    public static void main(String[] args) {
        SpringApplication.run(TestApplication .class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // My Profile Name:test
        System.out.println("My Profile Name:" + name);
    }
}

@ConfigurationProperties读取一组配置项

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

@Component
@ConfigurationProperties(prefix = "profile")
@Data
public class Profile {
    private String name;
    private String age;
}
@SpringBootApplication
public class TestApplication implements InitializingBean {
    @Autowired
    private Profile profile;

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Profile Object:" + profile.getName());
        System.out.println("Profile Object:" + profile.getAge());
    }
}

@PropertySource 读取配置文件

@SpringBootApplication
// 指定读取application.properties配置文件
@PropertySource("classpath:application.properties")
public class TestApplication implements InitializingBean {
    // 读取一个配置项,配置文件所属为application.properties配置文件
    @Value("${profile.name}")
    private String name;

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Name:" + name);
    }
}

        另外还可以使用 Environment 读取配置文件,Environment 是 Spring Core 中的一个用于读取配置文件的类,将此类使用 @Autowired 注入到类中就可以使用它的 getProperty 方法来获取某个配置项的值;还可以通过原生 Properties 对象来读取配置文件,在开发中常用的还是我上面进行举例的三种,这里列举的两种方式作为了解就好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那山川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值