1. @Value("${...}")
– 配置参数值注入
@Value("1")
- 注入值 1
@Value("${server.error.path}")
- 注入配置参数
server.error.path
的值 - 如果配置参数
server.error.path
未定义则注入失败,抛出异常IllegalArgumentException
java.lang.IllegalArgumentException: Could not resolve placeholder 'server.error.path' in value "${server.error.path}"
- 注入配置参数
@Value("${server.error.path:${error.path:/error}}")
- 注入配置参数
server.error.path
的值 - 如果配置参数
server.error.path
未定义,注入配置参数error.path
的值 - 如果配置参数
server.error.path
和error.path
都未定义,则使用值/error
- 注入配置参数
2. @Value("#{...}")
– SPEL
表达式求值注入
@Value("#{1}")
- 注入值
1
- 注入值
@Value("#{student.name}")
- 注入
bean
student
属性name
的值 - 如果
student
不存在或者其属性name
不存在,则抛出异常SpelEvaluationException
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'student' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?
- 注入
@Value("#{student.name ?: '张三'}")
- 注入
bean
student
的属性name
的值 - 如果
student
存在并且有属性name
,但属性值为null
,则注入值"张三"
- 注入
@Value("#{systemProperties['mongodb.port'] ?: 27017}")
- 注入系统属性
mongodb.port
的值 - 如果系统属性
mongodb.port
未设定,则注入值27017
- 注入系统属性
3. @Value("${...}")
和 @Value("#{...}")
混用
@Value("#{'${db.host:127.0.0.1}'}")
- 注入配置参数
db.host
- 如果配置参数
db.host
未设置,注入值127.0.0.1
- 注入配置参数