栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot读取配置文件的方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot读取配置文件的方式

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/756685.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号