欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot加载外部配置文件

程序员文章站 2022-03-04 18:53:22
...

使用注解

@PropertySource(value = {"classpath:/person.properties"},encoding = "UTF-8")
@PropertySource(value = {"classpath:/person.properties"},encoding = "UTF-8")
@Configuration
public class MainConfigOfPropertyValues {
    @Bean
    public Person person(){
        return new Person();
    }
}

获取方式
1.使用@Value注解

@Data
public class Person {
    @Value("#{12-2}")
    private Integer age;
    @Value("张三")
    private String name;
    @Value("${person.nickName}")
    private String nickName;

    public Person(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Person() {
    }
} 

2.使用environment 对象

 ConfigurableEnvironment environment = annotationConfigApplicationContext.getEnvironment();
        String property = environment.getProperty("person.nickName");
        System.out.println(property);