springboot读取配置文件的方式

本文介绍了两种在SpringBoot中读取配置文件并注入属性的方法。一种是通过@ConfigurationProperties注解在方法上,另一种是在类上使用该注解,并使用@EnableConfigurationProperties进行注册。示例中展示了如何注入并测试配置信息,如姓名和年龄。
摘要由CSDN通过智能技术生成

springboot读取配置文件的方式

1.通过@ConfigurationProperties(prefix = “com.sun”)注解作用在方法上

配置文件内容

com:
  sun:
    name: "暗夜"
    age: 18
  sun1:
    name: "第二个人"
    age: 19

首先我们定义一个类

@Data
public class Person {
    private String name;
    private int age;
}

建一个配置类

@Configuration
public class PersonConfig {
    @Bean
    //给定配置文件中需要注入属性的前缀 通过set get方法注入
    @ConfigurationProperties(prefix = "com.sun")
    public Person person(){
        return new Person();
    }
}

搞一个测试类

@SpringBootTest
class PersonTest {
    @Autowired
    private Person person;
    @Test
    public void fun(){
        System.out.println(person);//打印Person(name=暗夜, age=18)
    }
}
方案二

直接在类上使用@ConfigurationProperties注解并指定前缀

@Data
@ConfigurationProperties(prefix = "com.sun1")
public class Person {
    private String name;
    private int age;
}

在配置类中使用 @EnableConfigurationProperties(Person.class)注解 将使用@ConfigurationProperties的类注册到spring中

@Configuration
@EnableConfigurationProperties(Person.class)
public class Person2Config {
    @Bean
    public Person person2(){
        return new Person();
    }
}

测试

@SpringBootTest
class PersonTest {
     @Autowired
    private Person person;

     @Autowired
     @Resource(name = "person2")//通过name注入bean
     private Person person2;
    @Test
    public void fun(){
        System.out.println(person);//Person(name=暗夜, age=18)

        System.out.println(person2);//Person(name=第二个人, age=19)
    }
}

最后两个的测试成功

总结

使用@ConfigurationProperties注解作用在方法上时可直接使用

作用在类上的时候时 需要通过@EnableConfigurationProperties(##.class)在配置类中向spring ioc注册该类的bean

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值