首页 > 其他 > 详细

024 使用@PropertySoruce 注入配置文件

时间:2018-05-27 00:43:30      阅读:260      评论:0      收藏:0      [点我收藏+]

一 .概述

在前面我们说到,我们获取属性值的最大途径就是从外部的配置文件之中获取.

spring为我们提供了@PropertySoruce注解完成属性文件的属性值的获取.


 二 .测试

[1] 创建一个配置文件

trek.name=trek
trek.age=11

[2]配置类

@Configuration
@PropertySource(value="classpath:value.properties")
public class PropertyConfig {
    
    @Value("${trek.name}")
    private String  name ;
    
    @Value("${trek.age}")
    private Integer age;
    
    @Bean
    public Person person() {
        Person person = new Person();
        person.setName(name);
        person.setAge(age);
        return person;
    }
}

我们使用${}的方式将配置文件的属性注入到配置类之中.

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=PropertyConfig.class)
public class PropertyTest {
    @Autowired
    private ApplicationContext context;
    
    @Test
    public void test() {
        System.out.println(context.getBean("person"));
    }
}

就是那么简单,很容易就获取了配置文件的属性了.

024 使用@PropertySoruce 注入配置文件

原文:https://www.cnblogs.com/trekxu/p/9094883.html

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