03.Spring Framework 之组件赋值

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"));
    }

}
发布了37 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/masteryourself/article/details/96782282
今日推荐