Vlaue注解的详解
$ 符号对属性进行注入相当于占位符
普通字符串直接将字符串注入属性中
先对其进行占位符进行解析,然后将其替换后的字符串赋值给恰当字段
根据操作系统环境变量,jvm环境变量,properties文件,作为替换来源
@Component
public class UserService {
@Value("${sunbo}")
private String test;
public void test(){
System.out.println("====="+test);
}
}
```properties
sunbo=true
@ComponentScan("com.jinxiangyang") //扫描包
@PropertySource("classpath:spring.properties") //读取配置元
public class AppConfig {
}
# 先当与el表达式会对其进行解析
注:解析spring表达式得到的结果可能是字符串,也可能是一个bean对象
@Component
public class UserService {
@Value("#{sunbo}")
private String test;
public void test(){
System.out.println("====="+test);
}
}
@ComponentScan("com.jinxiangyang") //扫描包
//@PropertySource("classpath:spring.properties") //读取配置元
public class AppConfig {
}
@Component("sunbo")
public class OrderService {
}
类型不匹配
@Component
public class UserService {
@Value("#{sunbo}")
private OrderService test;
public void test() {
System.out.println("=====" + test);
}
}
@ComponentScan("com.jinxiangyang") //扫描包
//@PropertySource("classpath:spring.properties") //读取配置元
public class AppConfig {
}
@Component("sunbo")
public class OrderService {
}
对@Value的扩展
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${sunbo}")
public @interface SunboValue {
}