Spring通过注解注入外部配置文件

指定路径 使用 @PropertySource 指定配置文件路径,支持 properties 和 XML 的配置文件,但不支持 yml。 属性赋值 可以用注解 @Value 对属性直接赋值、${}获取配置文件的值、SPEL表达式#{}。...

指定路径

使用 @PropertySource 指定配置文件路径,支持 properties 和 XML 的配置文件,但不支持 yml。

属性赋值

可以用注解 @Value 对属性直接赋值、${}获取配置文件的值、SPEL表达式#{}。

  • 直接赋值:@Value("name jack")
  • 读取配置文件:@Value("${user.age}")
  • 指定默认值:@Value("${user.desc:default desc}") 表示如果没有user.desc的配置,则赋值为default desc
  • SPEL表达式:@Value("#{'${user.username}'?.toUpperCase()}") 表示将从配置文件读取的值转为大写,?可以不填,表示如果没有user.username的配置,则忽略

例子

user.properties 的内容

user.username=my name
user.age=24
#user.desc=

配置类

@Component
@PropertySource(value = {"classpath:user.properties"})
public final class UserProperties {
    @Value("name jack")
    private String name;

    @Value("${user.age}")
    private Integer age;

    @Value("#{'${user.username}'?.toUpperCase()}")
    private String username;

    @Value("${user.desc:default desc}")
    private String desc;
}

测试

public class Test {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(UserProperties.class);
    UserProperties bean = context.getBean(UserProperties.class);

    System.out.println(bean);
  }
}

输出结果

UserProperties(name=name jack, age=24, username=MY NAME, desc=default desc)
  • 发表于 2019-08-01 09:20
  • 阅读 ( 413 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除