Spring 注解 @Value和@PropertySource
一、@Value和@PropertySource
1、@Value
@Value注解:为属性赋值
赋值方式:
- 基本数值
- SpEl表达式 #{}
- ${},读取配置文件[xxx.properties]中的值,配合注解@PropertySource使用
@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();
}
2、@PropertySource
@PropertySource:读取外部配置文件中的key-value保存到运行的环境变量中
@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;
}
二、@Value和@PropertySource案例
1、项目结构
2、Person
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Person {
/**
* @Value赋值方式1:基本数值
*/
@Value("张三")
private String name;
/**
* @Value赋值方式2:SpEl表达式 #{}
*/
@Value("#{ 20-2 }")
private int age;
/**
* @Value赋值方式3:${},读取配置文件[xxx.properties]中的值
*/
@Value("${person.phone}")
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", phone='" + phone + '\'' +
'}';
}
}
3、配置类
import org.springframework.context.annotation.*;
/**
* 使用@PropertySource注解可以读取外部配置文件中的key-value保存到运行的环境变量中
*/
@PropertySource(value = {"classpath:/person.properties"},encoding = "UTF-8")
@ComponentScan({"com.dashu"})
@Configuration
public class BeanConfig {
}
4、外部文件person.properties
person.phone = 11111111
5、测试类
import com.dashu.bean.Person;
import com.dashu.config.BeanConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class Main {
public static void main(String[] args) {
//加载配置类获取容器
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
//容器中获取Person
Person person = annotationConfigApplicationContext.getBean(Person.class);
//打印
System.out.println(person);
System.out.println("--------------------");
/**
* 获取运行时环境实例
*/
ConfigurableEnvironment environment = annotationConfigApplicationContext.getEnvironment();
/**
* 根据外部文件的key,从环境中获取value
*/
String property = environment.getProperty("person.phone");
//打印
System.out.println(property);
}
}