zoukankan      html  css  js  c++  java
  • 十一、【注解】Spring注解@Value

    1. 首先定义实体
    /**
     * @author zhangjianbing
     * @date 2020年9月23日
     */
    @Data
    public class Apple {
    
        @Value("${apple.color}")
        private String color;
    
        @Value("红富士")
        private String name;
    
    }
    
    1. 属性文件test.properties放在resource下
    apple.color=red
    
    1. spring的配置类

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

    /**
     * @author zhangjianbing
     * @date 2020年9月23日
     */
    @Configuration
    @PropertySource(value = "classpath:/test.properties")
    public class AppleConfig {
    
        @Bean
        public Apple apple() {
            return new Apple();
        }
    
    }
    
    1. 测试
    /**
     * @author zhangjianbing
     * @date 2020年9月23日
     */
    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);
        }
    
    }
    
    1. 测试结果
    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
    
  • 相关阅读:
    R语言导入scv文件乱码问题及解决
    水论文而已,科研就交给恐龙吧
    R语言实现单因素方差分析带字母的显著性标记
    记录新的学习
    如果你的校园网连不上很有可能是因为IE代理服务出错导致无法上网
    git 补充
    git
    学习linux的菜鸟 shell脚本中的循环
    学习linux的菜鸟 shell脚本中的逻辑判断
    学习linux的菜鸟 shell脚本中的dat,计算器,内置变量的用法
  • 原文地址:https://www.cnblogs.com/zhangjianbing/p/13726689.html
Copyright © 2011-2022 走看看