Spring注解--@Value注解的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fangxinde/article/details/82794182

     使用@Value对bean实例的属性赋值,此注解可直接修饰属性,主要分三种情况:
    1、基本数值直接赋值
    2、可以写SpEL:#{}表达式通过运算进行赋值
    3、可以写${};取出配置文件【xxx.properties】中的值(在运行环境变量里面的值)进行赋值;

public class Person {
	@Value("Fangxinde")//属性name直接赋值
	private String name;
	@Value("#{35-2}")//通过表达式对属性age赋值
	private Integer age;
	@Value("${person.nickName}")//获取配置文件中值对属性nickName进行赋值
	private String nickName;
	
	public String getNickName() {
		return nickName;
	}
	public void setNickName(String nickName) {
		this.nickName = nickName;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	 
	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Person() {
		 System.out.println("创建对象");
	}
	
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", nickName="
				+ nickName + "]";
	}
	 
}

配置类:

@PropertySource中value值是配置文件的路径,把配置文件注册到容器,注解@Value("${person.nickName}")才能获取配置文件中的值

@PropertySource(value={"classpath:/person.properties"})//配置类中引入配置文件
@Configuration 
public class MainConfigOfPropertyValues {
	@Bean 
	public Person person(){
		System.out.println("创建bean");
		return new Person();
	}
}

 配置文件person.properties

public class IOCTest_PropertyValue {
	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
	@SuppressWarnings("resource")
	@Test
	public void test01(){
		System.out.println("容器创建完成.....");
		Person bean = applicationContext.getBean(Person.class);
		System.out.println(bean);
		applicationContext.close();
	}
	 
}

运行结果:

Person [name=Fangxinde, age=33, nickName=李次方]

猜你喜欢

转载自blog.csdn.net/fangxinde/article/details/82794182