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语法

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