九、Spring中使用@Value和@PropertySource为属性赋值

首先回顾下在xml中我们是如何为spring的bean进行属性赋值呢?

大体是这样的

	<bean id="person" class="com.atguigu.bean.Person"  scope="prototype" >
		<property name="age" value="18"></property>
		<property name="name" value="zhangsan"></property>
	</bean>

这样就能够为person对象的agename属性进行赋值。

那使用@Value注解怎么做呢?又如何取出配置文件中的值呢,就像取出jdbc.properties中的值一样。

public class Person {
	
	//使用@Value赋值;
	//1、基本数值
	//2、可以写SpEL; #{}
	//3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
	
	@Value("张三")
	private String name;
	@Value("#{20-2}")
	private Integer age;
	
	@Value("${person.nickName}")
	private String nickName;
    // 省略了getter、setter等
}

配置类:

//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
	
	@Bean
	public Person person(){
		return new Person();
	}

}

写个测试方法测试一下:

public class IOCTest_PropertyValue {
	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
	@Test
	public void test01(){
		printBeans(applicationContext);
		System.out.println("=============");
		
		Person person = (Person) applicationContext.getBean("person");
		System.out.println(person);
		
		
		ConfigurableEnvironment environment = applicationContext.getEnvironment();
		String property = environment.getProperty("person.nickName");
		System.out.println(property);
		applicationContext.close();
	}
	
	private void printBeans(AnnotationConfigApplicationContext applicationContext){
		String[] definitionNames = applicationContext.getBeanDefinitionNames();
		for (String name : definitionNames) {
			System.out.println(name);
		}
	}

}

打印出结果:

mainConfigOfPropertyValues
person
=============
Person [name=张三, age=18, nickName=小李四]
小李四

这两个注解非常简单,@Value注解支持不仅支持简单赋值,还支持spring El表达式赋值,关于springEL表达式,可以参考这篇:springEL表达式

@PropertySource 就是导入外部的配置文件。
注意:在@Value中,使用springEL表达式使用#,引入配置文件中的值使用$,此文也有体现。

今天就这么多。

你所看得到的天才不过是在你看不到的时候还在努力罢了!
原文地址:https://www.cnblogs.com/heliusKing/p/11396493.html