@Value
1
2
3
4
5
6
7
8
9
10
11
12
|
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
/**
* The actual value expression such as <code>#{systemProperties.myProp}</code>
* or property placeholder such as <code>${my.app.myProp}</code>.
*/
String value();
}
|
演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.eh.bean;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
@Data
public class Person {
//使用@Value赋值
//1、基本数值
//2、可以写SpEL; #{}
//3、可以写${};取出配置文件【properties】中的值(properties中的值会放在运行环境变量里面),需要结合注解@PropertySource一起使用,当然在配置文件中引入context-placeholder也是可以的
@Value("张三")
private String name;
@Value("#{20-2}")
private Integer age;
@Value("${person.nickName}")
private String nickName;
}
|
@PropertySource和@PropertySources
@PropertySource是可重复注解,同样可使用@PropertySources
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
String name() default "";
String[] value();
boolean ignoreResourceNotFound() default false;
String encoding() default "";
Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.atguigu.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import com.atguigu.bean.Person;
//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
|
从环境变量获取值
上面讲到@PropertySource是读取外部配置文件中的k/v保存到运行的环境变量中,理所当然运行时环境变量的值也可以直接获取或者使用@Value注解的$
取值方式从环境变量中取值
1
2
3
|
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.nickName");
System.out.println(property);
|