在属性上使用@Value

  1. package com.chentianyu.ba01;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.stereotype.Component;
  4. @Component("myStudent")
  5. public class Student {
  6. /**
  7. * @Value: 简单类型的属性赋值
  8. * 属性: value 是String类型的,表示简单类型的属性值
  9. * 位置: 1.在属性定义上面,无需set方法,推荐使用
  10. * 2.在set方法的上面
  11. */
  12. @Value(value = "张三")
  13. private String name;
  14. @Value(value = "29")
  15. private Integer age;
  16. public String getName() {
  17. return name;
  18. }
  19. /*public void setName(String name) {
  20. this.name = name;
  21. }*/
  22. public Integer getAge() {
  23. return age;
  24. }
  25. /*public void setAge(Integer age) {
  26. this.age = age;
  27. }*/
  28. @Override
  29. public String toString() {
  30. return "Student{" +
  31. "name='" + name + '\'' +
  32. ", age=" + age +
  33. '}';
  34. }
  35. }

测试类

  1. @Test
  2. public void test01(){
  3. String config = "applicationContext.xml";
  4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
  5. //从容器中获取对象(需要id(value里的就是id))
  6. Student student = (Student) applicationContext.getBean("myStudent");
  7. System.out.println(student);
  8. }
  1. Student{name='张三', age=29}

在set方法上使用@Value

package com.chentianyu.ba01;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("myStudent")
public class Student {
    /**
     * @Value: 简单类型的属性赋值
     * 属性: value 是String类型的,表示简单类型的属性值
     * 位置: 1.在属性定义上面,无需set方法,推荐使用
     *      2.在set方法的上面
     */
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    /*public void setName(String name) {
        this.name = name;
    }*/

    public Integer getAge() {
        return age;
    }
    @Value("30")
    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
@Test
public void test01(){
    String config = "applicationContext.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
    //从容器中获取对象(需要id(value里的就是id))
    Student student = (Student) applicationContext.getBean("myStudent");
    System.out.println(student);
}
Student{name='null', age=30}

getBean()底层是一个Map