普通字符串
直接把字符串赋值给当前字段
@Configuration
public class MyConfig {
@Value("ijunfu")
private String author;
public String author() {
return author;
}
}
占位符
先进行占位符的替换,然后将替换后的字符串赋值给当前字段
//application.yml
author: ijunfu
@Configuration
public class MyConfig {
@Value("${author}")
private String author;
public String author(){
return author;
}
}
可根据操作系统环境变量、JVM环境变量、properties文件作为数据源。
需要注意的是,如果对应的值不存在,比如:
@Value("${author2}")
private String author;
启动Spring则直接报错:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XXX' Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'author2' in value "${author2}"
SpringEL
先解析Spring表达式,然后将结果赋值给当前字段
@Configuration
public class MyConfig {
@Bean("author")
public String author() {
return "ijunfu";
}
}
@Slf4j
@SpringBootTest
class MyConfigTest {
@Value("#{author}")
private String author;
@Test
void print_author() {
log.info("author={}", author);
}
}
注意:解析Spring表达式得到的结果可以是字符串,也可以是一个Bean对象。
基于@Value扩展
解析注解上@Value,并将值赋值给当前字段
1.定义配置文件
//application.yml
local:
server:
port: 9000
2.定义注解
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${local.server.port}")
public @interface LocalServerPort {
}
3.定义配置类
@Configuration
public class MyConfig {
@LocalServerPort
private Integer port;
public Integer getPort() {
return port;
}
}
小结
综上所述,@Value有四种使用方式:
- 普通字符串
- 占位符
- SpringEL
- 基于@Value扩展。