Spring中使用@Value註解實現給Bean屬性賦值

屬性賦值

只用Spring註解開發的時候,可以使用@Value搭配@PropertySource註解進行給Bean的屬性進行賦值。

@Value

@Value註解的定義:

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {

	/**
	 * The actual value expression: for example {@code #{systemProperties.myProp}}.
	 */
	String value();
}

可以看到@Value註解接受的參數只能是字符串,所以使用時參數都需要帶上雙引號。並且可以在屬性,方法,參數等位置上標註。value屬性支持以下三種類型:

  1. 基本數據類型,包括String,int,boolean等類型。
  2. SpEL,#{}的形式即表示使用SpEL表達式,一般用於獲取環境中其他bean的屬性,當使用Elivis運算符“表達式1?:表達式2”,比如#{ “obj.property? :default_value” }形式時,這裏的obj是取當前容器中的對象,default_value就是前面的值爲空時的默認值。
  3. 在主配置類中通過@PropertySource註解加載配置文件,然後通過${ property : default_value}的形式取配置文件中的值,其中default_value表示前面的值爲空時的默認值。

測試

1.在添加了Spring依賴的Maven項目中創建以下兩個實體類Student類和Teacher類

public class Teacher {
	public int id;
	public String name;
	
	public Teacher() {
		// TODO Auto-generated constructor stub
	 System.out.println("teacher-----創建");
	}
	
	
	public Teacher(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}	
//省略getter和setter方法
}

在Student類中使用${}取配置文件的值,#{}取容器中的teacher對象的name屬性

public class Student{
	
	@Value("1")
	private int id;
	@Value("${student.name}")
	private String name;
	@Value("${student.address:北京}")
	private String address;
	@Value("#{teacher.name?:'老子'}")
	private String teacherName;
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", address=" + address + ", teacherName=" + teacherName + "]";
	}
//省略getter和setter方法
}

2.在resources目錄下創建一個配置文件person.properties,添加以下值:

student.name=張三
person.address=廣州市

3.創建配置類,使用@PropertySource註解讀取外部配置文件person.properties中的key/value保存到運行的環境變量中。

@Configuration
@PropertySource("person.properties")
public class SpringConfig2 {	
    @Bean
	public Student student() {
		return new Student();		
	}
    @Bean
	public Teacher teacher() {
		//return new Teacher(2,"老李");
		return new Teacher();
	}
}

4.創建測試類進行測試,編寫代碼獲取容器中的id爲student的bean和直接獲取配置環境的屬性值。

public class IoCTest {
	@Test
	public void test() {
		//獲取Spring的IOC容器
		AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig2.class);
		//從容器中獲取bean
       Student stu = (Student) applicationContext.getBean("student");
       System.out.println(stu);			
	    //獲取環境變量
		ConfigurableEnvironment environment = applicationContext.getEnvironment();
		String property = environment.getProperty("person.address");
		System.out.println(property);
		//關閉容器
		applicationContext.close();
	}
}

5.測試結果:
在這裏插入圖片描述


拓展閱讀:
SpEL語法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章