美文网首页永远学不完的JAVA
spring常用注解及源码解析(三)

spring常用注解及源码解析(三)

作者: 超速蜗牛1984 | 来源:发表于2019-08-23 13:46 被阅读0次

属性赋值相关注解的基本用法

@Value

1、基本数值
2、可以写SpEL表达式,#{}
Demo
在BEAN类文件中在变量上加@Value

 @Value("yiyi")
    private String name;
    @Value("#{20-2}")
    private Integer age;

@PropertySource

1、在配置类上加上@PropertySource,获取配置文件中的属性

//使用@PropertySource读取外部文件中的属性
@PropertySource(value={"classpath:/application.properties"})
@Configuration
public class MainConfigOfPropertyValues {
    @Bean
    public Person person(){
        return new Person();
    }
}

2、在Bean类文件中,需要引用配置文件中的属性值的变量上加上 @Value("${属性文件中需要获取的属性的KEY值}")

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

额外补充说明
配置文件中的属性及属性值会在运行时加载到运行环境中,所以

 ConfigurableEnvironment environment= (ConfigurableEnvironment) applicationContext.getEnvironment();
        String property = environment.getProperty("配置文件中的KEY值");

也可以拿到想要拿到的值,在需要的时候使用

相关文章

网友评论

    本文标题:spring常用注解及源码解析(三)

    本文链接:https://www.haomeiwen.com/subject/utozsctx.html