首页 > 编程语言 > 详细

九、Spring中使用@Value和@PropertySource为属性赋值

时间:2019-08-22 20:18:46      阅读:107      评论:0      收藏:0      [点我收藏+]

首先回顾下在xml中我们是如何为spring的bean进行属性赋值呢?

大体是这样的

    <bean id="person" class="com.atguigu.bean.Person"  scope="prototype" >
        <property name="age" value="18"></property>
        <property name="name" value="zhangsan"></property>
    </bean>

这样就能够为person对象的agename属性进行赋值。

那使用@Value注解怎么做呢?又如何取出配置文件中的值呢,就像取出jdbc.properties中的值一样。

public class Person {
    
    //使用@Value赋值;
    //1、基本数值
    //2、可以写SpEL; #{}
    //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
    
    @Value("张三")
    private String name;
    @Value("#{20-2}")
    private Integer age;
    
    @Value("${person.nickName}")
    private String nickName;
    // 省略了getter、setter等
}

配置类:

//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
    
    @Bean
    public Person person(){
        return new Person();
    }

}

写个测试方法测试一下:

public class IOCTest_PropertyValue {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
    @Test
    public void test01(){
        printBeans(applicationContext);
        System.out.println("=============");
        
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
        
        
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty("person.nickName");
        System.out.println(property);
        applicationContext.close();
    }
    
    private void printBeans(AnnotationConfigApplicationContext applicationContext){
        String[] definitionNames = applicationContext.getBeanDefinitionNames();
        for (String name : definitionNames) {
            System.out.println(name);
        }
    }

}

打印出结果:

mainConfigOfPropertyValues
person
=============
Person [name=张三, age=18, nickName=小李四]
小李四

这两个注解非常简单,@Value注解支持不仅支持简单赋值,还支持spring El表达式赋值,关于springEL表达式,可以参考这篇:springEL表达式

@PropertySource 就是导入外部的配置文件。
注意:在@Value中,使用springEL表达式使用#,引入配置文件中的值使用$,此文也有体现。

今天就这么多。

九、Spring中使用@Value和@PropertySource为属性赋值

原文:https://www.cnblogs.com/heliusKing/p/11396493.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!