spring(四):spring中给bean的属性赋值

spring中给bean的属性赋值

  • xml文件properties标签设置
    <bean id="student" class="com.enjoy.study.cap10.Student" >
            <property name="id" value="18"/>
            <property name="name" value="wxf"/>
    </bean>
  • 注解
    • @Autowired
    • @Value
    • @Resource

本章博客重点介绍注解赋值的使用

@Autowired

@Value

@Configuration
public class CapMainConfig {
    @Bean
    public Student student(){
        return new Student();
    }
}

public class TestCap {
    @Test
    public void testMethod(){
        ApplicationContext context = new AnnotationConfigApplicationContext(CapMainConfig.class);
        Student student = (Student) context.getBean("student");
        System.out.println("student = " + student);
    }
}

字符形式@Value("")

public class Student {
    @Value("12")
    private Integer id;
    @Value("wxf")
    private String name;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

结果

student = Student{id=12, name='wxf'}

表达式@Value("${}")、@Value("#{}")

通过@Value("${}") 可以获取对应属性文件中定义的属性值

@Value("#{}") 表示SpEl表达式,通常用来获取bean的属性,或者调用bean的某个方法

猜你喜欢

转载自www.cnblogs.com/qf123/p/10932431.html