Spring源码窥探之:@Value

1. 首先定义实体

/**
 * @author 70KG
 * @Title: Apple
 * @Description: 苹果实体
 * @date 2018/10/22下午9:26
 * @From www.nmyswls.com
 */
@Data
public class Apple {

    @Value("${apple.color}")
    private String color;

    @Value("红富士")
    private String name;

}

2. 属性文件test.properties放在resource下

apple.color=red

3. spring的配置类

@PropertySource(value = "classpath:/test.properties")将属性文件读取到内存中

/**
 * @author 70KG
 * @Title: AppleConfig
 * @Description: 配置类
 * @date 2018/10/22下午9:28
 * @From www.nmyswls.com
 */
@Configuration
@PropertySource(value = "classpath:/test.properties")
public class AppleConfig {

    @Bean
    public Apple apple() {
        return new Apple();
    }

}

4. 测试

/**
 * @author 70KG
 * @Title: Test01
 * @Description: test
 * @date 2018/10/22下午9:30
 * @From www.nmyswls.com
 */
public class Test01 {

    @Test
    public void test01() {
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(AppleConfig.class);
        // 从容器中获取所有的bean
        String[] names = app.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println("bean的名字--->" + name);
        }
        Apple apple = (Apple) app.getBean("apple");
        System.out.println(apple);

        System.out.println("==========IOC容器创建完成==========");

        ConfigurableEnvironment environment = app.getEnvironment();
        String property = environment.getProperty("apple.color");
        System.out.println("获取配置文件中的属性---->" + property);
    }

}

5. 测试结果

bean的名字--->org.springframework.context.annotation.internalConfigurationAnnotationProcessor
bean的名字--->org.springframework.context.annotation.internalAutowiredAnnotationProcessor
bean的名字--->org.springframework.context.annotation.internalRequiredAnnotationProcessor
bean的名字--->org.springframework.context.annotation.internalCommonAnnotationProcessor
bean的名字--->org.springframework.context.event.internalEventListenerProcessor
bean的名字--->org.springframework.context.event.internalEventListenerFactory
bean的名字--->appleConfig
bean的名字--->apple
Apple(color=red, name=红富士)
==========IOC容器创建完成==========
获取配置文件中的属性---->red

前面的都是bean的后置处理器

转载于:https://www.cnblogs.com/zhangjianbing/p/9834879.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值