spring中@PropertySource和@Value注解使用
@PropertySource注解用于导入外部配置文件,以使用导入的属性
下面是配置文件中的一个属性
zhang.email=zhang@163.com
下面是配置类,在配置类中使用@PropertySource注解导入配置文件
import com.annotation.entities.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@PropertySource(value = "classpath:Person.properties")
@Configuration
public class MainConfigPropertie {
@Bean
public Person person(){
return new Person();
}
}
@Value注解用于为属性赋值,可以赋值为常量,或者使用SpEL表达式,也可以使用${}去上面配置类中导入的配置文件中的属性
import org.springframework.beans.factory.annotation.Value;
public class Person {
public Person() {
System.out.println("创建perosn对象");
}
public Person(Integer id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
private Integer id;
@Value("小张")
private String name;
@Value("${zhang.email}")
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
使用@PropertySource注解导入的配置文件中的属性回被放入到运行环境中,所以也可以直接使用运行时环境类获取配置文件中的属性
@Test
public void testValue(){
ConfigurableEnvironment environment = annotationConfigApplicationContext.getEnvironment();
String property = environment.getProperty("zhang.email");
System.out.println(property);
}
还没有评论,来说两句吧...