spring读取外部配置文件

在开发中我们经常有些值是在不确定的,需要运行时才赋确定的值(比如数据库连接ip地址,开发时可能用本地数据库测试,上线时就改用服务器数据库 ),还有如果在每个地方都硬编码写死了,之后要改就很麻烦。所以我们希望可以将这些值写到外部配置文件,如果要进行修改就直接修改配置文件而不用动源码。

使用@PropertySource注解和Environment

@PropertySource:通过这个注解可以导入一份properties格式的配置文件进行解析

Environment:通过@PropertySource解析的文件属性会保存在Environment中

@Configuration
@PropertySource("classpath:app.properties")
public class TestConfig {
    @Autowired
    Environment env;
    @Bean
    public Student getStudent(){
        return new Student(env.getProperty("student.id"),
                env.getProperty("student.name"));
    }
}

在本例中,@PropertySource引用了类路径中一个名为app.properties的文件,app.properties文件内容如下:

student.id=1725110
student.name=zdl

这个属性文件会加载到Environment中,env.getProperty()就是从Environment检索属性。

getProperty()方法有四个重载的变种形式:

String getProperty(String key)//获取不到值就为null
String getProperty(String key,String defaultValue)//获取不到值就赋值默认值defaultValue
T getProperty(String key,Class<T> type)//将获取到的字符串值转成type类型
T getProperty(String key,Class<T> type,T defaultValue)//将获取到的字符串值转成type类型,如果没有就赋值defaultValue

getRequiredProperty()//获取不到值就抛出异常

使用@Value

在上面的例子中,需要我们获取到Environment对象,调用getProperty()方法获取对应的属性。如果使用@Value比较方便.

@Value("${student.id}")

${student.id}是一个占位符,需要配置PropertySourcesPlaceholderConfigurer才能解析,不够springboot好像默认就配置了,@Value()就可以把占位符表示的属性注入到变量中。

首先在配置类中配置PropertySourcesPlaceholderConfigurer和导入配置文件app.properties

@Configuration
@PropertySource("classpath:app.properties")
public class TestConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

}

然后在实体类中通过@Value引用配置文件的属性了

@Component
@PropertySource("classpath:app.properties")
public class Student {

    @Value("${student.id}")
    private String id;

    @Value("${student.name}")
    private String name;

}

通过这样的方式引用的值就会注入到对象的属性中;

除了可以注入到属性中,还可以注入到方法的参数中

比如:

@Component
@PropertySource("classpath:app.properties")
public class Student {
    private String id;
    private String name;

    public Student(@Value("${student.id}") String id,@Value("${student.name}") String name) {
        this.id = id;
        this.name = name;
    }
}

posted on 2020-05-15 14:15  ggsdduzdl  阅读(346)  评论(0编辑  收藏  举报

导航