Spring注解驱动开发学习总结7:属性赋值@Value详解

Spring注解驱动开发学习总结7:属性赋值@Value详解

1、属性赋值

给bean的属性赋值,可以使用@Value注解添加属性初始值
1)可以添加基本数值
2)可以写Spring的SpEL表达式:#{}
3)可以写${},取出配置文件[properties]中的值。同时需要在配置文件上使用@PropertySource注解,标明配置文件的类路径。

以下还是以之前创建的Person类进行举例,来给属性赋值。

1.1 创建配置文件

创建配置文件:person.properties。

person.age=18

1.2 Person类添加属性赋值

Person类添加属性赋值,使用@Value注解。
这里我们对name字段,使用@Value注解直接赋值。
对age字段,我们从配置文件中取出person.age的值进行赋值

package com.example.bean;

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

public class Person {
    @Value("zhangsan")
    private String name;

    @Value("${person.age}")
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

1.3 新建配置文件

新建配置文件:com/example/config/MainConfigOfPropertyValue.java。
在配置文件上使用@PropertySource注解,标明配置文件的路径

package com.example.config;

import com.example.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@PropertySource(value = {"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValue {
    @Bean
    public Person person() {
        return new Person();
    }
}

1.4 测试

新建测试方法:testPropertyValue。

	@Test
    public void testPropertyValue() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValue.class);
        System.out.println("\nioc容器已创建完成\n");

        Object person = applicationContext.getBean("person");
        System.out.println(person);
        applicationContext.close();
    }

运行结果见下图。
可以看到,已经成功给person实例属性进行了赋值。
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值