03.Spring Framework 之组件赋值

本文详细介绍了Spring框架中属性注入的两种主要方式:@Value和@PropertySource的使用方法及环境搭建过程。通过实例展示了如何利用这些注解进行基本数值赋值、SpEL表达式、配置文件值读取及默认值设定。

1. @Value

1.1 使用方式

@Value:给属性赋值,有四种用法

  • 基本数值

  • 可以写 SpEL,#{}

  • 可以写 ${};取出配置文件 properties 中的值(在运行环境变量里面的值)

  • : 后面可以跟上默认值

1.2 环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-framework/tutorial-spring-framework-property 工程

1. Person
@Data
@Component
public class Person {

    @Value("#{001+001}")
    private Long id;

    @Value("zs")
    private String name;

    @Value("${person.address}")
    private String address;

    @Value("${person.age:19}")
    private Integer age;

}

2. @PropertySource

2.1 使用方式

@PropertySource:读取外部配置文件中的 k/v 保存到运行的环境变量中,加载完外部的配置文件以后使用 ${} 取出配置文件的值

2.2 环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-framework/tutorial-spring-framework-property 工程

1. SpringConfig
@Configuration
@PropertySource(value = "classpath:person.properties")
@ComponentScan("pers.masteryourself.tutorial.spring.framework.property")
public class SpringConfig {

}
2. PropertyApplication
public class PropertyApplication {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        Person person = context.getBean(Person.class);
        // Person{id=2, name='zs', address='china', age=19}
        System.out.println(person);
        // china
        System.out.println(context.getEnvironment().getProperty("person.address"));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值