zoukankan      html  css  js  c++  java
  • spring学习(二十)--spring注解之@Value

    通过@Value将外部的值动态注入到Bean中,使用的情况有:

    • 注入普通字符串
    • 注入操作系统属性
    • 注入表达式结果
    • 注入其他Bean属性:注入beanInject对象的属性another
    • 注入文件资源
    • 注入URL资源

      详细代码见:

       @Value("normal")
        private String normal; // 注入普通字符串
    
        @Value("#{systemProperties['os.name']}")
        private String systemPropertiesName; // 注入操作系统属性
    
        @Value("#{ T(java.lang.Math).random() * 100.0 }")
        private double randomNumber; //注入表达式结果
    
        @Value("#{beanInject.another}")
        private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面
    
        @Value("classpath:com/hry/spring/configinject/config.txt")
        private Resource resourceFile; // 注入文件资源
    
        @Value("http://www.baidu.com")
        private Resource testUrl; // 注入URL资源

    示例:获取application.properties中的name字段值,以及通过Resource获取properties文件的内容

    spring-annotion.xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
    
            <!-- 支持@Value获取properties中的值 -->
            <bean id="appProperty" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                <property name="locations">
                    <array>
                        <value>classpath:application.properties</value>
                    </array>
                </property>
            </bean>
        
        <!-- 配置自动扫描的包 -->
        <context:component-scan base-package="springAnnotions"></context:component-scan>
    
    </beans>

    applicatio.properties

    name=littleball

    ValueAnnotion.java

    package springAnnotions;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Properties;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.core.io.Resource;
    import org.springframework.stereotype.Component;
    
    @Componentpublic class ValueAnnotion {
        
        //冒号后边的:qiaozhong为默认值,当从properties中没有取到name的时候,就取默认值给name
        @Value("${name:qiaozhong}")
        private String name;
        
        @Value("classpath:application.properties")
        private Resource resource;
        
        public static void main(String[] args) throws IOException {
            ApplicationContext aContext = new ClassPathXmlApplicationContext("classpath:springConfig/spring-annotions.xml");
            ValueAnnotion valueAnnotion = aContext.getBean(ValueAnnotion.class);
            System.out.println(valueAnnotion.getName());
            File file = valueAnnotion.getResource().getFile();
            if (valueAnnotion.getResource().isReadable()) {
                System.out.println(getFileContent(valueAnnotion.getResource().getInputStream()));
                System.out.println(getFileContent(file, "name"));
            }
        }
        
        public String getName(){
            return name;
        }
        
        public Resource getResource(){
            return resource;
        }
        
        /**
         * 获取file文件的内容
         * @param is
         * @throws IOException
         */
        public static String getFileContent(InputStream is) throws IOException {
            String result = "";
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line=br.readLine()) != null) {
                    result += line;
                }
                if (is != null) {
                    is.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
        
        /**
         * 获取file文件中key对应的value
         * @param file
         * @return
         */
        public static String getFileContent(File file, String key){
            try {
                if (file.exists()) {
                    Properties propertie = new Properties();
                    propertie.load(new FileInputStream(file));
                    return propertie.getProperty(key);
                }
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    执行结果:

    littleball
    name=littleball
    littleball
    个人理解,如有错误,欢迎指正!
  • 相关阅读:
    国外的零日漏洞记录片(中文字幕)
    浅谈网络爬虫中广度优先算法和代码实现
    浅谈网络爬虫中深度优先算法和简单代码实现
    Python正则表达式的简单应用和示例演示
    Python正则表达式初识(十)附正则表达式总结
    Python正则表达式初识(九)
    Python正则表达式初识(八)
    Python正则表达式初识(七)
    Python正则表达式初识(六)
    Python正则表达式初识(五)
  • 原文地址:https://www.cnblogs.com/gllegolas/p/11808817.html
Copyright © 2011-2022 走看看